Created
January 16, 2025 08:23
-
-
Save leo493852107/c8774c7311fb52266cf2ad8574362414 to your computer and use it in GitHub Desktop.
springboot全局异常处理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.lgd985.tx.advice; | |
| import com.lgd985.tx.common.R; | |
| import com.lgd985.tx.exception.BizException; | |
| import org.springframework.validation.BindingResult; | |
| import org.springframework.validation.FieldError; | |
| import org.springframework.web.bind.MethodArgumentNotValidException; | |
| import org.springframework.web.bind.annotation.ExceptionHandler; | |
| import org.springframework.web.bind.annotation.RestControllerAdvice; | |
| import java.util.HashMap; | |
| /** | |
| * @author 李建舜 | |
| * @version 1.0 | |
| * @date 2025/1/16 13:19 | |
| * @description | |
| */ | |
| @RestControllerAdvice | |
| public class GlobalExceptionHandler { | |
| // 参数校验异常处理 | |
| @ExceptionHandler(MethodArgumentNotValidException.class) | |
| public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { | |
| // result: 封装所有校验失败的字段和错误信息 | |
| BindingResult result = e.getBindingResult(); | |
| HashMap<String, String> errorMap = new HashMap<>(); | |
| for (FieldError fieldError: result.getFieldErrors()) { | |
| // 获取字段名 | |
| String field = fieldError.getField(); | |
| // 获取字段的错误信息 | |
| String defaultMessage = fieldError.getDefaultMessage(); | |
| errorMap.put(field, defaultMessage); | |
| } | |
| return R.error(500, "参数校验失败", errorMap); | |
| } | |
| // 业务异常处理 | |
| @ExceptionHandler(BizException.class) | |
| public R handleBizException(BizException e) { | |
| Integer code = e.getCode(); | |
| String msg = e.getMsg(); | |
| return R.error(code, msg); | |
| } | |
| // 最终兜底异常处理 | |
| @ExceptionHandler(Throwable.class) | |
| public R error(Throwable e) { | |
| return R.error(500, e.getMessage()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment