笔记之spring全局异常处理

使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,只要设计得当,就再也不用在 Controller 层进行 try-catch 了!而且,@Validated 校验器注解的异常,也可以一起处理,无需手动判断绑定校验结果 BindingResult/Errors 了
一、优缺点
优点:将 Controller 层的异常和数据校验的异常进行统一处理,减少模板代码,减少编码量,提升扩展性和可维护性。
缺点:只能处理 Controller 层未捕获(往外抛)的异常,对于 Interceptor(拦截器)层的异常,Spring 框架层的异常,就无能为力了
二、基本使用示例
@ControllerAdvice 注解定义全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {
}
请确保此 GlobalExceptionHandler 类能被扫描到并装载进 Spring 容器中
@ExceptionHandler 注解声明异常处理方法
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}
方法 handleException() 就会处理所有 Controller 层抛出的 Exception 及其子类的异常,这是最基本的用法了。
被 @ExceptionHandler 注解的方法的参数列表里
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {


    /**
      * Exceptions handled by the annotated method. If empty, will default to any
      * exceptions listed in the method argument list.
      */
    Class<? extends Throwable>[] value() default {};


}
如果 @ExceptionHandler 注解中未声明要处理的异常类型,则默认为参数列表中的异常类型
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler()
    @ResponseBody
    String handleException(Exception e){
        return "Exception Deal! " + e.getMessage();
    }
}
参数对象就是 Controller 层抛出的异常对象
三、处理 Service 层上抛的业务异常
封装的业务异常类:
public class BusinessException extends RuntimeException {


    public BusinessException(String message){
        super(message);
    }
}
Service 实现类
@Service
public class DogService {


    @Transactional
    public Dog update(Dog dog){


        // some database options


        // 模拟狗狗新名字与其他狗狗的名字冲突
        BSUtil.isTrue(false, "狗狗名字已经被使用了...");


        // update database dog info


        return dog;
    }


}
其中辅助工具类BSUtil
public static void isTrue(boolean expression, String error){
    if(!expression) {
        throw new BusinessException(error);
    }
}
在 GlobalExceptionHandler 类中声明该业务异常类,并进行相应的处理,然后返回给用户。更贴近真实项目的代码
/**
 * Created by kinginblue on 2017/4/10.
 * @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    AppResponse handleException(Exception e){
        LOGGER.error(e.getMessage(), e);


        AppResponse response = new AppResponse();
        response.setFail("操作失败!");
        return response;
    }


    /**
     * 处理所有业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    AppResponse handleBusinessException(BusinessException e){
        LOGGER.error(e.getMessage(), e);


        AppResponse response = new AppResponse();
        response.setFail(e.getMessage());
        return response;
    }
}
四、处理 Controller 数据绑定、数据校验的异常
在 Dog 类中的字段上的注解数据校验规则
@Data
public class Dog {


    @NotNull(message = "{Dog.id.non}", groups = {Update.class})
    @Min(value = 1, message = "{Dog.age.lt1}", groups = {Update.class})
    private Long id;


    @NotBlank(message = "{Dog.name.non}", groups = {Add.class, Update.class})
    private String name;


    @Min(value = 1, message = "{Dog.age.lt1}", groups = {Add.class, Update.class})
    private Integer age;
}
说明:@NotNull、@Min、@NotBlank 这些注解的使用方法,不在本文范围内。如果不熟悉,请查找资料学习即可。


其他说明:
@Data 注解是 **Lombok** 项目的注解,可以使我们不用再在代码里手动加 getter & setter。
在 Eclipse 和 IntelliJ IDEA 中使用时,还需要安装相关插件,这个步骤自行Google/Baidu 吧!
SpringMVC 中对于 RESTFUL 的 Json 接口来说,数据绑定和校验,是这样的:
/**
 * 使用 GlobalExceptionHandler 全局处理 Controller 层异常的示例
 * @param dog
 * @return
 */
@PatchMapping(value = "")
AppResponse update(@Validated(Update.class) @RequestBody Dog dog){
    AppResponse resp = new AppResponse();


    // 执行业务
    Dog newDog = dogService.update(dog);


    // 返回数据
    resp.setData(newDog);


    return resp;
}
使用 @Validated + @RequestBody 注解实现。
当使用了 @Validated + @RequestBody 注解但是没有在绑定的数据对象后面跟上 Errors 类型的参数声明的话,Spring MVC 框架会抛出 MethodArgumentNotValidException 异常。


所以,在 GlobalExceptionHandler 中加上对 MethodArgumentNotValidException 异常的声明和处理,就可以全局处理数据校验的异常了
/**
 * Created by kinginblue on 2017/4/10.
 * @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {


    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    AppResponse handleException(Exception e){
        LOGGER.error(e.getMessage(), e);


        AppResponse response = new AppResponse();
        response.setFail("操作失败!");
        return response;
    }


    /**
     * 处理所有业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    AppResponse handleBusinessException(BusinessException e){
        LOGGER.error(e.getMessage(), e);


        AppResponse response = new AppResponse();
        response.setFail(e.getMessage());
        return response;
    }


    /**
     * 处理所有接口数据验证异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    AppResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        LOGGER.error(e.getMessage(), e);


        AppResponse response = new AppResponse();
        response.setFail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return response;
    }
}


此处理解 :定义全局异常处理器 通过 controllerAdvice 以及ExceptionHandler  注解 将拦截所有 controller层的异常 可以对拦截的异常类型进行 区分并 进行相应处理
   例如错误日志打印 以及 异常的友好响应 (这里可以自定义异常类需要继承RuntimeException 对异常的属性 进行个性化定制 如 添加 错误码 以及 错误信息字段 还有异常信息 可以 继承自RuntimeException)
   此处响应 可以 分装成Respose对象 字段分别有(success boolean类型;errorCode 、errorMsg、以及数据体 data Object类型)

猜你喜欢

转载自blog.csdn.net/u011445756/article/details/80174683
今日推荐