一、添加配置类:
代码语言:javascript复制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.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import java.util.HashSet;
import java.util.Set;
/**
* @author zcqshine
* @date 2019/11/7
*/
@Configuration
public class ContainerConfig {
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
return factory -> {
Set<ErrorPage> set = new HashSet<>();
set.add(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
factory.setErrorPages(set);
};
}
}
二、继承并改写500异常类
代码语言:javascript复制import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* @author zcqshine
* @date 2019/11/7
*/
@Controller
public class MyBasicErrorController extends BasicErrorController {
public MyBasicErrorController() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
@RequestMapping(produces = "text/html",value = "/500")
public ModelAndView errorHtml500(HttpServletRequest request, HttpServletResponse response) {
response.setStatus(getStatus(request).value());
Map<String, Object> model = getErrorAttributes(request,isIncludeStackTrace(request, MediaType.TEXT_HTML));
model.put("msg","自定义错误信息");
return new ModelAndView("error/500", model);
}
@RequestMapping(value = "/500")
@ResponseBody
public ResponseEntity<Map<String,Object>> error500(HttpServletRequest request){
Map<String,Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.APPLICATION_JSON));
HttpStatus status = getStatus(request);
body.put("message","系统错误");
return new ResponseEntity<>(body,status);
}
}