Spring统一异常处理框架

RestControllerAdvice

@RestControllerAdvice是Spring Framework 4.3的一个新特性,它是一个结合了@ControllerAdvice + @ResponseBody的注解。因此@RestControllerAdvice能够帮助咱们经过一个横切点@ExceptionHandler来使用RestfulApi处理异常。bash

通用异常异常

@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);
  }
}
复制代码

异常处理框架ui

@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;
  }
}
复制代码
相关文章
相关标签/搜索