1.前言
项目经常会出现各种异常情况,如果所有都使用try-catch语句,无疑代码重复率相当的高,恰巧Spring给我们解决了这个问题:
@ExceptionHandler配置这个注解可以处理异常, 但是仅限于当前Controller中处理异常。
那么有没有什么办法可以让所有controller都处理呢,恰巧也有:
@ControllerAdvice是一个增强的controller,可以配置basePackage下的所有controller. 所以结合两者使用,就可以处理全局的异常了.
2.代码
package com.zsl.springboot.bootdemo.utils;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
*
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 系统发生500异常的处理方式
* @param e 指定处理的异常
* @return
*/
@ExceptionHandler(RuntimeException.class)
public String customException(Exception e) {
return "error";
}
}
通过这种配置,我们项目当中出现异常的地方,都会准确的跳到error界面。
上面这种对于500的异常以及可以处理了,那么对于404的资源又该怎么处理呢?
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer = factory -> {
ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND,"/404");
factory.addErrorPages(errorPage);
};
return webServerFactoryCustomizer;
}
同一个controlleradvice下面增加这个bean即可做到
Github源码:https://github.com/managerlu/bootdemo