0    课程地址

https://coding.imooc.com/lesson/380.html#mid=28594

 

1    浓缩精华
1.1    4.1

 

2    个人关注
2.1    4.1

2.2    异常处理

 

@ExceptionHandler可以对指定异常进行拦截

 

 @ExceptionHandler(value = CouponException.class)
    public CommonResponse<String> handleExceptionAdvice(HttpServletRequest req,CouponException ex){
        CommonResponse<String> response = new CommonResponse<>(
                -1,"业务异常"
        );

 

 

 

 

3    课程内容
3.1    为什么要统一异常处理

1  低耦合,责任权利分离,模块化管理

2  便于敏捷开发

3  返回友好异常提示

 

4    代码演练
4.1    相关demo

异常定义类

package com.imooc.coupon.exception;

/**
 * CouponException
 *  <h1>优惠券统一异常定义</h1>
 * @author 魏豆豆
 * @date 2021/8/5
 */
public class CouponException extends Exception {

    public CouponException(String message){
        super(message);
    }
}

 

 

全局异常处理类

package com.imooc.coupon.advice;

import com.imooc.coupon.exception.CouponException;
import com.imooc.coupon.vo.CommonResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * GlobalExceptionAdvice
 * <h1>全局异常处理</h1>
 * @author 魏豆豆
 * @date 2021/8/5
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 对CouponException异常进行统一处理
     * @param req
     * @param ex
     * @return
     */
    @ExceptionHandler(value = CouponException.class)
    public CommonResponse<String> handleExceptionAdvice(HttpServletRequest req,CouponException ex){
        CommonResponse<String> response = new CommonResponse<>(
                -1,"业务异常"
        );
        response.setData(ex.getMessage());
        return response;
    }

}

 

 

 

 

 




posted on 2021-01-19 07:34  菜鸟乙  阅读(89)  评论(0编辑  收藏  举报