Commit 7d17caf4c0ba7fd7755e03cd83c04c73127fa221
1 parent
e4ffe1ee
新增自定义异常和全局异常捕获
Showing
2 changed files
with
66 additions
and
0 deletions
src/main/java/com/cnlive/shenhe/config/GlobalExceptionHandlerAdvice.java
0 → 100644
| 1 | +package com.cnlive.shenhe.config; | |
| 2 | + | |
| 3 | +import com.cnlive.shenhe.bean.ErrorEnum; | |
| 4 | +import com.cnlive.shenhe.bean.ResponseBean; | |
| 5 | +import lombok.extern.slf4j.Slf4j; | |
| 6 | +import org.springframework.web.bind.annotation.ExceptionHandler; | |
| 7 | +import org.springframework.web.bind.annotation.RestControllerAdvice; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * @Author: yan-zhao-wang | |
| 11 | + * @DateTime: 2022-09-20 9:08 | |
| 12 | + */ | |
| 13 | +@Slf4j | |
| 14 | +@RestControllerAdvice | |
| 15 | +public class GlobalExceptionHandlerAdvice { | |
| 16 | + /** | |
| 17 | + * 自定义运行时异常 | |
| 18 | + * | |
| 19 | + * @param e | |
| 20 | + * @return | |
| 21 | + */ | |
| 22 | + @ExceptionHandler(MyException.class) | |
| 23 | + public ResponseBean handleMyException(MyException e) { | |
| 24 | + log.info("运行时异常为:{}", e.getMessage()); | |
| 25 | + return new ResponseBean(666, e.getMessage(), null); | |
| 26 | + } | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * 其它全局异常 | |
| 30 | + * | |
| 31 | + * @param e | |
| 32 | + * @return | |
| 33 | + */ | |
| 34 | + @ExceptionHandler(Exception.class) | |
| 35 | + public ResponseBean handleException(Exception e) { | |
| 36 | + log.info("其它异常为:{}", e.getMessage()); | |
| 37 | + return new ResponseBean(ErrorEnum.ERROR, null); | |
| 38 | + } | |
| 39 | +} | ... | ... |
src/main/java/com/cnlive/shenhe/config/MyException.java
0 → 100644
| 1 | +package com.cnlive.shenhe.config; | |
| 2 | + | |
| 3 | +import lombok.AllArgsConstructor; | |
| 4 | +import lombok.Data; | |
| 5 | +import lombok.EqualsAndHashCode; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * @Author: yan-zhao-wang | |
| 9 | + * @DateTime: 2022-09-20 9:03 | |
| 10 | + */ | |
| 11 | +@EqualsAndHashCode(callSuper = true) | |
| 12 | +@Data | |
| 13 | +@AllArgsConstructor | |
| 14 | +public class MyException extends RuntimeException { | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * 错误码 | |
| 18 | + */ | |
| 19 | + private Integer code; | |
| 20 | + | |
| 21 | + /** | |
| 22 | + * 错误描述 | |
| 23 | + */ | |
| 24 | + private String msg; | |
| 25 | + | |
| 26 | + | |
| 27 | +} | ... | ... |