第一章-自定义异常
自定义异常
java实现自定义异常
选择的继承的异常有:
- Throwable
- Exception
- RuntimeException
可以选择其中一个类进行继承,这里选择继承RuntimeException为例;

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
充分享受每一天

浙公网安备 33010602011771号