以ArithmeticException异常为例,当除数为0时报该异常,例:2/0
会报异常Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.example.study.controller.TestController.main(TestController.java:21)
@RestControllerAdvice
public class GlobleExceptionHandle {
//括号内可填写具体的异常,这样这个方法就只会捕捉这个异常
@ExceptionHandler(ArithmeticException.class)
public String numberException(ArithmeticException e, HttpServletRequest request){
StringBuffer requestURL = request.getRequestURL();
//返回信息可以自定义,例如自定义response结构来设置code和message
return requestURL+"地址出现错误,错误信息为"+e.getMessage();
}
}
示例:
定义一个controller测试
@RestController
public class TestController {
@GetMapping("/test")
public String test(){
System.out.println(1/0);
return "success";
}
}
当请求中出现ArithmeticException异常后,会被自定义异常信息捕捉并返回自定义信息
请求中无异常时正常返回数据@RestController
public class TestController {
@GetMapping("/test")
public String test(){
System.out.println(1/2);
return "success,无异常";
}
}



