@RestControllerAdvice实现springboot全局异常类不生效问题_BellCalderon的博客-CSDN博客_restcontrolleradvice不生效

1、先创建一个自定义CustomException 类

public class CustomException extends RuntimeException
{

private static final long serialVersionUID = 1L;

private Integer code;

private String message;

public CustomException(String message)
{
    this.message = message;
}

public CustomException(String message, Integer code)
{
    this.message = message;
    this.code = code;
}

public CustomException(String message, Throwable e)
{
    super(message, e);
    this.message = message;
}

@Override
public String getMessage()
{
    return message;
}

public Integer getCode()
{
    return code;
}

}

2、创建全局异常类

/**
* 全局异常处理器
*
* @author zz
*/
@RestControllerAdvice
public class GlobalExceptionHandler {

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

/\*\*
 \* 业务异常
 */
@ExceptionHandler(CustomException.class)
public Result businessException(CustomException e) {
    if (StringUtils.isNull(e.getCode()))
    {
        return Result.error(e.getMessage());
    }
    return Result.error(e.getCode(), e.getMessage());
}



@ExceptionHandler(Exception.class)
public Result handleException(Exception e)
{
    log.error(e.getMessage(), e);
    return Result.error(e.getMessage());
}


/\*\*
 \* 参数校验  validation 验证异常
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public Object validExceptionHandler(MethodArgumentNotValidException e) {
    ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
    String message = objectError.getDefaultMessage();
    return Result.error(message);
}

}

这样觉得没有问题,但是在使用的时候是不生效的 如图:

那只换一种方式

1、先创建 InterceptorConfig

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
    resolvers.add(new BusinessExceptionHandler());
}

}

2、继承HandlerExceptionResolver 类

/**
* 实现异常类的处理
*/
@Component
public class BusinessExceptionHandler implements HandlerExceptionResolver {

@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
    if(e instanceof CustomException) {
        modelAndView.addObject("msg", ((CustomException) e).getMessage());
        modelAndView.addObject("code", ((CustomException) e).getCode());
    }else  if(e instanceof MethodArgumentNotValidException){
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = ((MethodArgumentNotValidException)e).getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
        modelAndView.addObject("msg", objectError.getDefaultMessage());
        modelAndView.addObject("code", HttpStatus.PARAMETER);
    }

    return modelAndView;
}

}

验证效果:实现全局异常。


原网址: 访问
创建于: 2022-04-13 10:24:06
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论