Spring统一异常处理框架

RestControllerAdvice

@RestControllerAdvice是Spring Framework 4.3的一个新特性,它是一个结合了@ControllerAdvice + @ResponseBody的注解。所以@RestControllerAdvice可以帮助我们通过一个横切点@ExceptionHandler来使用RestfulApi处理异常。

通用异常异常

@RestControllerAdvice
public class MyExceptionTranslator {

  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.OK)
  public String handleNotFoundException(CustomNotFoundException ex) {
    return ex.getMessage();
  }
}
复制代码

自定义异常处理

自定义异常类

public class CustomNotFoundException extends RuntimeException{
  public CustomNotFoundException(String msg) {
    super(msg);
  }
}
复制代码

异常处理框架

@RestControllerAdvice
public class MyExceptionTranslator {

  @ExceptionHandler(Exception.class)
  @ResponseStatus(HttpStatus.OK)
  public String handleNotFoundException(CustomNotFoundException ex) {
    return ex.getMessage();
  }
  
  //自定义的异常处理
  @ExceptionHandler(CustomNotFoundException.class)
  @ResponseStatus(HttpStatus.OK)
  public ResponseMsg handleNotFoundException(CustomNotFoundException ex) {
    ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
    return responseMsg;
  }
}
复制代码

转载于:https://juejin.im/post/5d0b5ed8f265da1b80204c42

猜你喜欢

转载自blog.csdn.net/weixin_33875839/article/details/93179800