美文网首页
@ControllerAdvice + @ExceptionHa

@ControllerAdvice + @ExceptionHa

作者: kayabu | 来源:发表于2018-09-23 13:55 被阅读0次
  1. 在全局异常处理类上标记@ControllerAdvice
    确保该处理类能被扫描到并装载进spring容器
@ControllerAdvice
public class GlobalExceptionHandler {
}
  1. 在相应的处理异常方法上添加@ExceptionHandler(被处理的Exception.class),该方法会处理被处理的Exception及其子类
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}

或者这样写,参数中添加异常参数

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler()
    @ResponseBody
    String handleException(Exception e){
        return "Exception Deal! " + e.getMessage();
    }
}

相关文章

网友评论

      本文标题:@ControllerAdvice + @ExceptionHa

      本文链接:https://www.haomeiwen.com/subject/muafoftx.html