Spring统一异常处理框架

3,566 阅读1分钟

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;
  }
}