全局异常捕获(支出@Valid)

时间:2021-08-20
本文章向大家介绍全局异常捕获(支出@Valid),主要包括全局异常捕获(支出@Valid)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package com.test3.handler;

import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;

import com.test3.utils.JsonResult;
import com.test3.utils.MsgEnum;
import com.test3.utils.MyException;

/**
 * 异常捕获rest处理
 */
@ControllerAdvice
public class ExceptionHandler extends ExceptionHandlerExceptionResolver{
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);
    public static final String DEFAULT_ERROR_VIEW = "error";
    
    @SuppressWarnings("unchecked")
    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult<Object> handle(Exception e) {
        e.printStackTrace();
        if (e instanceof MyException) {
            MyException mye = (MyException) e;
            return JsonResult.errorResult(mye.getCode(), mye.getMessage());
        } else if(e instanceof BindException) { // 非@RequestBody参数
            BindException ex = (BindException)e;
            String msg = ex.getBindingResult().getAllErrors().stream()
                    .filter(FieldError.class::isInstance)
                    .map(FieldError.class::cast)
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining());
            return JsonResult.errorResult(5, msg);
        } else if (e instanceof MethodArgumentNotValidException) { //@RequestBody 参数
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e;
            String msg = ex.getBindingResult().getAllErrors().stream()
                .filter(FieldError.class::isInstance)
                .map(FieldError.class::cast)
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining());
            return JsonResult.errorResult(6, msg);
        }else {
            logger.error("未知异常:", e);
            if (e.getMessage() != null && e.getMessage().startsWith("Failed to convert value of type")) {
                return JsonResult.errorResult(MsgEnum.PARAMTYPE_ERROR);
            } else {
                return JsonResult.errorResult(MsgEnum.UNKNOW_ERROR);
            }
        }
    }
    
    
    //这里是异常页面跳转,一般不使用, 注意需要加@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class) 才能用
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
    
    
}

1.加上@Valid

public JsonResult mytestnormal(@RequestBody @Valid TestRequest tq) 

2.TestRequest.java中加上验证注解

@NotBlank(message="标题不能为空!")
private String title;

无聊我就学英语

原文地址:https://www.cnblogs.com/trump2/p/15166793.html