springboot处理异常,实现异常页面
想代替springboot自带的白页
法1.通过@ControllerAdvice和@ExceptionHandler处理项目上下文出现的异常
步骤
- 自定义异常类(自定义异常类的时候可以结合枚举描述异常类)
//自定义异常
public class CustomizeException extends RuntimeException {
private String message;
/**
* 获取枚举类传入的错误消息
* @param errorCode
*/
public CustomizeException(ICustomizeErrorCode errorCode) {
this.message=errorCode.getMessage();
}
@Override
public String getMessage() {
return message;
}
}
//接口
public interface ICustomizeErrorCode {
String getMessage();
}
//定义枚举
public enum CustomizeErrorCode implements ICustomizeErrorCode {
QUESTION_NOT_FOUND("你找到问题不在了,要不要换个试试?");
private String message;
@Override
public String getMessage() {
return message;
}
CustomizeErrorCode(String message) {
this.message = message;
}
}
- 在程序中可能出现的异常的地方抛出自定义异常
- 由带有@ControllerAdvice和@ExceptionHandler的类拦截和处理
//对所有异常进行拦截
@ControllerAdvice
public class CustomizeExceptionHandler {
//异常处理
@ExceptionHandler(CustomizeException.class)
public ModelAndView handlerException(Model model,
Throwable e){
//判断异常类型
if (e instanceof CustomizeException){
model.addAttribute("message",e.getMessage());
}else {
model.addAttribute("message","服务器冒烟了,要不然你稍后再试试");
}
return new ModelAndView("error");
}
}
这种方式只能处理上下文出现的异常,其他不能处理的异常害得依靠法儿来解决
法二:
方式1:我们可以新建error文件夹下面新建4xx.html和5xx.html 来处理异常,这是默认的处理方式
方式2:当我希望所有异常处理都渲染到同一个html页面上,所有不用上面的方法,通过实现ErrorController,使SpringBoot自定义的BasicErrorController
类失效 ,自定义我们自己的Controller
@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
//当ioc容器中存在实现了ErrorController的类是这个类的逻辑就失效了
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes,
ObjectProvider<ErrorViewResolver> errorViewResolvers) {
return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
errorViewResolvers.orderedStream().collect(Collectors.toList()));
}
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomizeErrorController implements ErrorController {
@Override
public String getErrorPath() {
return "error";
}
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request,
Model model){
HttpStatus status = getStatus(request);
if (status.is4xxClientError()){
model.addAttribute("message","你这个请求错了,试试换换!!!");
}
if (status.is5xxServerError()){
model.addAttribute("message","服务器冒烟了,要不然你稍后再试试!!!");
}
return new ModelAndView("error");
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
try {
return HttpStatus.valueOf(statusCode);
}
catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
}