springboot处理异常,实现异常页面

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;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值