全局异常捕获

在“javax.validation 与 Spring Boot 集成”章节您应该发现了,javax.validation 默认给出来的异常信息很丑,如下图:

全局异常捕获

此时,为我们可以利用 Spring Boot 的全局异常捕获进行处理,将输出的错误信息进行格式化,例如:

package com.hxstrive.springboot.validation.handler;

import com.hxstrive.springboot.validation.dto.CommonResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 全局异常处理
 * @author hxstrive.com
 * @since 1.0.0  2024/2/2 9:15
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

   /**
    * 捕获 ConstraintViolationException 异常,并处理,该异常由验证框架抛出
    */
   @ExceptionHandler(value = {ConstraintViolationException.class})
   public CommonResult<?> handleResourceNotFoundException(ConstraintViolationException e) {
       Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
       StringBuilder strBuilder = new StringBuilder();
       for (ConstraintViolation<?> violation : violations) {
           strBuilder.append(violation.getMessage()).append("\n");
       }

       CommonResult<?> response = new CommonResult<>();
       response.setState(false);
       response.setMessage(strBuilder.toString());
       return response;
   }

   /**
    * 捕获 MethodArgumentNotValidException 异常,并处理,该异常由验证框架抛出
    */
   @ExceptionHandler(value = {MethodArgumentNotValidException.class})
   public CommonResult<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
       BindingResult bindingResult = e.getBindingResult();
       List<ObjectError> errorList = bindingResult.getAllErrors();

       String message = null;
       if(!errorList.isEmpty()) {
           message = Optional.ofNullable(errorList.get(0)).map(ObjectError::getDefaultMessage).orElse("");
       }

       CommonResult<?> response = new CommonResult<>();
       response.setState(false);
       response.setMessage(Optional.ofNullable(message).orElse(e.getMessage()));
       return response;
   }

   /**
    * 搂底的异常处理,正常来讲不应该走到这里的,如果走到这里需要特别注意
    */
   @ExceptionHandler(value = Exception.class)
   public CommonResult<?> defaultErrorHandler(Exception e) {
       CommonResult<?> response = new CommonResult<>();
       response.setState(false);
       response.setMessage("服务器错误,请稍后重试");
       return response;
   }

}

添加了全局异常捕获后,重启应用程序,再次使用 ApiFox 访问接口,输出的错误信息更具可读性,如下图:

全局异常捕获

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号