概述
SpringBoot 提供了 @ControllerAdvice 、@RestControllerAdvice 注解可以实现统一异常处理,只需要在定义异常类加上以上注解即可。
自定义异常处理
定义统一异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String,Object> exceptionHandler(Exception e){
logger.error("系统异常Exception===",e);
Map<String,Object> result = new HashMap<String,Object>();
result.put("respCode", "9999");
result.put("respMsg", "怎么又出错了");
return result;
}
@ExceptionHandler(ServiceException.class)
@ResponseBody
public Map<String,Object> exceptionHandler(ServiceException ex){
logger.info("自定义异常ServiceException:{}({})",ex.getMsg(), ex.getCode());
Map<String,Object> result = new HashMap<String,Object>();
result.put("respCode", ex.getCode());
result.put("respMsg", ex.getMsg());
return result;
}
}
创建 controller 类
@RestController
@RequestMapping("/ex")
public class ExceptionController {
private Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping("/testEx")
public String testEx() {
logger.debug("testEx>>>>>>");
throw new ServiceException("501","自定义ServiceException异常");
}
@RequestMapping("/testEx1")
public String testEx1() {
logger.debug("testEx1>>>>>>");
int a = 1/0;
return "sucesss";
}
@RequestMapping("/test")
public String test() {
logger.debug("test>>>>>>");
return "sucesss";
}
}
测试异常
http://127.0.0.1:8080/ex/test 正常访问
http://127.0.0.1:8080/ex/testEx 自定义异常
http://127.0.0.1:8080/ex/testEx1 系统异常
tomcat further occurrences of HTTP header parsing errors will be logged at DEBUG level.
原访问地址: http://localhost:8080/ex/test
改为:http://127.0.0.1:8080/ex/test
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)