SpringBoot如何实现处理全局统一异常?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
在后端发生异常或者是请求出错时,前端通常显示如下
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.Fri Jun 07 15:38:07 CST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
对于用户来说非常不友好。
本文主要讲解如何在SpringBoot应用中使用统一异常处理。
实现方式
第一种:使用@ControllerAdvice和@ExceptionHandler注解
@Slf4j @ControllerAdvice public class GlobalExceptionHandler { @ResponseBody @ExceptionHandler(NullPointerException.class) public BaseResult globalException(HttpServletResponse response,NullPointerException ex){ log.info("GlobalExceptionHandler..."); log.info("错误代码:" + response.getStatus()); BaseResult result = new WebResult(WebResult.RESULT_FAIL,"request error:"+response.getStatus() ,"GlobalExceptionHandler:"+ex.getMessage()); return result; } }