|
| 1 | +在上一篇文章中我介绍了: |
| 2 | + |
| 3 | +1. 使用 `@ControllerAdvice` 和 `@ExceptionHandler` 处理全局异常 |
| 4 | +2. `@ExceptionHandler` 处理 Controller 级别的异常 |
| 5 | +3. `ResponseStatusException` |
| 6 | + |
| 7 | +通过这篇文章,可以搞懂如何在 Spring Boot 中进行异常处理。但是,光是会用了还不行,我们还要思考如何把异常处理这部分的代码写的稍微优雅一点。下面我会以我在工作中学到的一点实际项目中异常处理的方式,来说说我觉得稍微优雅点的异常处理解决方案。 |
| 8 | + |
| 9 | +下面仅仅是我作为一个我个人的角度来看的,如果各位读者有更好的解决方案或者觉得本文提出的方案还有优化的余地的话,欢迎在评论区评论。 |
| 10 | + |
| 11 | +## 最终效果展示 |
| 12 | + |
| 13 | +下面先来展示一下完成后的效果,当我们定义的异常被系统捕捉后返回给客户端的信息是这样的: |
| 14 | + |
| 15 | + |
| 16 | + |
| 17 | +返回的信息包含了异常下面 5 部分内容: |
| 18 | + |
| 19 | +1. 唯一标示异常的 code |
| 20 | +2. HTTP状态码 |
| 21 | +3. 错误路径 |
| 22 | +4. 发生错误的时间戳 |
| 23 | +5. 错误的具体信息 |
| 24 | + |
| 25 | +这样返回异常信息,更利于我们前端根据异常信息做出相应的表现。 |
| 26 | + |
| 27 | +## 异常处理核心代码 |
| 28 | + |
| 29 | +`ErrorCode.java` (此枚举类中包含了异常的唯一标识、HTTP状态码以及错误信息) |
| 30 | + |
| 31 | +```java |
| 32 | +import org.springframework.http.HttpStatus; |
| 33 | + |
| 34 | + |
| 35 | +public enum ErrorCode { |
| 36 | + RESOURCE_NOT_FOUND(1001, HttpStatus.NOT_FOUND, "未找到该资源"), |
| 37 | + REQUEST_VALIDATION_FAILED(1002, HttpStatus.BAD_REQUEST, "请求数据格式验证失败"); |
| 38 | + private final int code; |
| 39 | + |
| 40 | + private final HttpStatus status; |
| 41 | + |
| 42 | + private final String message; |
| 43 | + |
| 44 | + ErrorCode(int code, HttpStatus status, String message) { |
| 45 | + this.code = code; |
| 46 | + this.status = status; |
| 47 | + this.message = message; |
| 48 | + } |
| 49 | + |
| 50 | + public int getCode() { |
| 51 | + return code; |
| 52 | + } |
| 53 | + |
| 54 | + public HttpStatus getStatus() { |
| 55 | + return status; |
| 56 | + } |
| 57 | + |
| 58 | + public String getMessage() { |
| 59 | + return message; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public String toString() { |
| 64 | + return "ErrorCode{" + |
| 65 | + "code=" + code + |
| 66 | + ", status=" + status + |
| 67 | + ", message='" + message + '\'' + |
| 68 | + '}'; |
| 69 | + } |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +**`ErrorReponse.java`(返回给客户端具体的异常对象)** |
| 74 | + |
| 75 | +```java |
| 76 | +import org.springframework.util.ObjectUtils; |
| 77 | + |
| 78 | +import java.time.Instant; |
| 79 | +import java.util.HashMap; |
| 80 | +import java.util.Map; |
| 81 | + |
| 82 | +public class ErrorReponse { |
| 83 | + private int code; |
| 84 | + private int status; |
| 85 | + private String message; |
| 86 | + private String path; |
| 87 | + private Instant timestamp; |
| 88 | + private HashMap<String, Object> data = new HashMap<String, Object>(); |
| 89 | + |
| 90 | + public ErrorReponse() { |
| 91 | + } |
| 92 | + |
| 93 | + public ErrorReponse(BaseException ex, String path) { |
| 94 | + this(ex.getError().getCode(), ex.getError().getStatus().value(), ex.getError().getMessage(), path, ex.getData()); |
| 95 | + } |
| 96 | + |
| 97 | + public ErrorReponse(int code, int status, String message, String path, Map<String, Object> data) { |
| 98 | + this.code = code; |
| 99 | + this.status = status; |
| 100 | + this.message = message; |
| 101 | + this.path = path; |
| 102 | + this.timestamp = Instant.now(); |
| 103 | + if (!ObjectUtils.isEmpty(data)) { |
| 104 | + this.data.putAll(data); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | +// 省略 getter/setter 方法 |
| 109 | + |
| 110 | + @Override |
| 111 | + public String toString() { |
| 112 | + return "ErrorReponse{" + |
| 113 | + "code=" + code + |
| 114 | + ", status=" + status + |
| 115 | + ", message='" + message + '\'' + |
| 116 | + ", path='" + path + '\'' + |
| 117 | + ", timestamp=" + timestamp + |
| 118 | + ", data=" + data + |
| 119 | + '}'; |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +``` |
| 124 | + |
| 125 | +**`BaseException.java`(继承自 `RuntimeException` 的抽象类,可以看做系统中其他异常类的父类)** |
| 126 | + |
| 127 | +```java |
| 128 | +import org.springframework.util.ObjectUtils; |
| 129 | + |
| 130 | +import java.util.HashMap; |
| 131 | +import java.util.Map; |
| 132 | + |
| 133 | +/** |
| 134 | + * @author shuang.kou |
| 135 | + */ |
| 136 | +public abstract class BaseException extends RuntimeException { |
| 137 | + private final ErrorCode error; |
| 138 | + private final HashMap<String, Object> data = new HashMap<>(); |
| 139 | + |
| 140 | + public BaseException(ErrorCode error, Map<String, Object> data) { |
| 141 | + super(format(error.getCode(), error.getMessage(), data)); |
| 142 | + this.error = error; |
| 143 | + if (!ObjectUtils.isEmpty(data)) { |
| 144 | + this.data.putAll(data); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + protected BaseException(ErrorCode error, Map<String, Object> data, Throwable cause) { |
| 149 | + super(format(error.getCode(), error.getMessage(), data), cause); |
| 150 | + this.error = error; |
| 151 | + if (!ObjectUtils.isEmpty(data)) { |
| 152 | + this.data.putAll(data); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + private static String format(Integer code, String message, Map<String, Object> data) { |
| 157 | + return String.format("[%d]%s:%s.", code, message, ObjectUtils.isEmpty(data) ? "" : data.toString()); |
| 158 | + } |
| 159 | + |
| 160 | + public ErrorCode getError() { |
| 161 | + return error; |
| 162 | + } |
| 163 | + |
| 164 | + public Map<String, Object> getData() { |
| 165 | + return data; |
| 166 | + } |
| 167 | + |
| 168 | +} |
| 169 | +``` |
| 170 | + |
| 171 | +**`ResourceNotFoundException.java` (自定义异常)** |
| 172 | + |
| 173 | +可以看出通过继承 `BaseException` 类我们自定义异常会变的非常简单! |
| 174 | + |
| 175 | +```java |
| 176 | +import java.util.Map; |
| 177 | + |
| 178 | +public class ResourceNotFoundException extends BaseException { |
| 179 | + |
| 180 | + public ResourceNotFoundException(Map<String, Object> data) { |
| 181 | + super(ErrorCode.RESOURCE_NOT_FOUND, data); |
| 182 | + } |
| 183 | +} |
| 184 | +``` |
| 185 | + |
| 186 | +**`GlobalExceptionHandler.java`(全局异常捕获)** |
| 187 | + |
| 188 | +`@ExceptionHandler` 捕获异常的过程中,会优先找到最匹配的。 |
| 189 | + |
| 190 | +```java |
| 191 | +/** |
| 192 | + * @author shuang.kou |
| 193 | + */ |
| 194 | +@ControllerAdvice(assignableTypes = {ExceptionController.class}) |
| 195 | +@ResponseBody |
| 196 | +public class GlobalExceptionHandler { |
| 197 | + |
| 198 | + @ExceptionHandler(BaseException.class) |
| 199 | + public ResponseEntity<?> handleAppException(BaseException ex, HttpServletRequest request) { |
| 200 | + String path = request.getRequestURI(); |
| 201 | + ErrorReponse representation = new ErrorReponse(ex, path); |
| 202 | + return new ResponseEntity<>(representation, new HttpHeaders(), ex.getError().getStatus()); |
| 203 | + } |
| 204 | + |
| 205 | + |
| 206 | + @ExceptionHandler(value = ResourceNotFoundException.class) |
| 207 | + public ResponseEntity<ErrorReponse> handleResourceNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) { |
| 208 | + ErrorReponse errorReponse = new ErrorReponse(ex, request.getRequestURI()); |
| 209 | + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorReponse); |
| 210 | + } |
| 211 | +} |
| 212 | + |
| 213 | +``` |
| 214 | + |
| 215 | +## 写一个抛出异常的类测试 |
| 216 | + |
| 217 | +**`Person.java`** |
| 218 | + |
| 219 | +```java |
| 220 | +public class Person { |
| 221 | + private Long id; |
| 222 | + private String name; |
| 223 | + |
| 224 | + // 省略 getter/setter 方法 |
| 225 | +} |
| 226 | +``` |
| 227 | + |
| 228 | +**`ExceptionController.java`(抛出一场的类)** |
| 229 | + |
| 230 | +```java |
| 231 | +@RestController |
| 232 | +@RequestMapping("/api") |
| 233 | +public class ExceptionController { |
| 234 | + |
| 235 | + @GetMapping("/resourceNotFound") |
| 236 | + public void throwException() { |
| 237 | + Person p=new Person(1L,"SnailClimb"); |
| 238 | + throw new ResourceNotFoundException(ImmutableMap.of("person id:", p.getId())); |
| 239 | + } |
| 240 | + |
| 241 | +} |
| 242 | +``` |
| 243 | + |
0 commit comments