一、背景
在我们编写程序的过程中,程序中可能随时发生各种异常,那么我们如何优雅的处理各种异常呢?
二、需求
1、拦截系统中部分异常,返回自定义的响应。
比如:
系统发生HttpRequestMethodNotSupportedException
异常,我们需要返回如下信息。
http的状态码:返回 405
{
code: 自定义异常码,
message: 错误消息
}
2、实现自定义异常的拦截
拦截我们自己写的 BizException
三、编写一些异常基础代码
1、引入jar包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
注意:
引入spring-boot-starter-validation
是为了验证请求的中的参数,然后当参数不满足时抛出异常。
2、定义一个自定义异常
public class BizException extends RuntimeException {
public BizException() {
}
public BizException(String message) {
super(message);
}
public BizException(String message, Throwable cause) {
super(message, cause);
}
public BizException(Throwable cause) {
super(cause);
}
public BizException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}