springboot异常处理的通用方式3

2022-10-02 12:05:32

3、按原来的方式使用异常类,返回给前端的时候返回的就是异常的枚举值

4、定义统一的异常处理方法处理springmvc的异常
4.1、GlobalExceptionHandler类
4.2、标注了@RestControllerAdvice注解,说明会把错误码通过json格式返回

//```java
@RestControllerAdvice
public class GlobalExceptionHandler {

private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

/**
 * 自定义异常
 *
 * @param serverRuntimeException
 * @return
 */
@ExceptionHandler(ServerRuntimeException.class)
public ResponseEntity<Map<String, Object>> beanServerRuntimeException(ServerRuntimeException serverRuntimeException) {
    LoggerUtils.error(LOGGER, serverRuntimeException, "server runtime exception, detail={}", serverRuntimeException);
    Map<String, Object> result = new HashMap<>();
    String message = serverRuntimeException.getServerErrCodeDefine().getMessageSourceKey();
    try{
        String internationalization =LocaleMessageUtils.getMessage(serverRuntimeException.getServerErrCodeDefine().getMessageSourceKey());
        if(StringUtils.isNotBlank(internationalization)){
            message = internationalization;
        }
    }catch (Exception e){
    }
    result.put("code", serverRuntimeException.getServerErrCodeDefine().getCode());
    result.put("message",message);
    result.put("errCode", serverRuntimeException.getServerErrCodeDefine().getErrCode());
    LoggerUtils.error(LOGGER, serverRuntimeException, "server runtime exception, message={}", result);
    return ResponseEntity.status(serverRuntimeException.getServerErrCodeDefine().getHttpStatus()).body(result);
}

}

  • 作者:yuchangyuan5237
  • 原文链接:https://blog.csdn.net/yuchangyuan5237/article/details/118083116
    更新时间:2022-10-02 12:05:32