Spring異常解析器HandlerExceptionResolver


一、spring異常解析器

1. 為什么使用:系統產生的異常,如果沒被捕獲,會返回給客戶端,用戶會看到看不懂的異常信息,體驗不好

2. 作用:全局異常捕獲,統一處理異常

3. HandlerExceptionResolver接口

public interface HandlerExceptionResolver {
    @Nullable
    ModelAndView resolveException(HttpServletRequest var1, HttpServletResponse var2, @Nullable Object var3, Exception var4);
}

 

二、定義自己的異常解析器,實現HandlerExceptionResolver

@Component
@Slf4j
public class BusinesExceptionHandler implements HandlerExceptionResolver {
    private static String errorMsg = "服務器繁忙,請稍后嘗試";
    private static String nullErrorMsg = "null";

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        modelAndView.addObject("message", msg);
        modelAndView.addObject("code", code);
        return modelAndView;
    }
}

 

三、把自定義的異常解析器,注冊到異常解析器列表

@Configuration
@Slf4j
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new BusinesExceptionHandler());
    }
}

 

 

 

 

參考:

https://blog.csdn.net/qq_22172133/article/details/82147630

https://www.cnblogs.com/taiguyiba/p/11817930.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM