Springboot-主线1-自定义异常

自定义异常

java实现自定义异常

选择的继承的异常有:

  • Throwable
  • Exception
  • RuntimeException

可以选择其中一个类进行继承,这里选择继承RuntimeException为例;

image-20201114140913225

Springboot的自定义异常

在以往的java自定义异常之后,我们还需要对全局异常进行处理。

/*
    全局定义异常
 */
@ControllerAdvice
public class SelfExceptionHandler {
    // 类似于RequestMapping 如果抛出这个SelfException的异常,就会执行此方法
    @ExceptionHandler(SelfException.class)
    @ResponseBody
    public Response handle(SelfException se){
        return ResponseUtils.error(se.getCode(),se.getMessage());
    }

}

自定义处理界面

​ 在一般项目中都会有400、500和404这种的异常页面,针对每个异常页面都会设计相应的页面布局和样式,也只有这样的错误页面才会让普通用户看着容易接受。

其实Springboot把默认把异常的处理都集中到一个ModelAndView中。

配置错误注册

@Component
public class ErrorPageConfig implements ErrorPageRegistrar {

    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/errorPage/400");
        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/errorPage/401");
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errorPage/404");
        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errorPage/500");
        registry.addErrorPages(error400Page, error401Page, error404Page, error500Page);
    }
}

配置Controller

@Controller
@RequestMapping("/errorPage")
public class ErrorPageController {

    @RequestMapping("/{code}")
    public String toErrorPage(@PathVariable int code) {
        return "error/" + code;
    }

}

配置yaml

spring:
	mvc:
        static-path-pattern: /static/**
        view:
          prefix: classpath:/templates/
          suffix: .html
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值