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

package com.test3.handler;

import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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 com.test3.utils.JsonResult;
import com.test3.utils.MsgEnum;
import com.test3.utils.MyException;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常捕获rest处理
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandler extends ExceptionHandlerExceptionResolver{
    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) {
        log.error("出现异常:",e);
        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 if (e instanceof HttpMessageNotReadableException) { // 参数类型或格式问题或为空
        	if(e.getCause()!=null) {
        		return JsonResult.errorResult(MsgEnum.PARAM_ERROR);
        	} else {
        		return JsonResult.errorResult(MsgEnum.PARAM_IS_NULL);
        	}
        } else {
            logger.error("未知异常:", e);
            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;
    }
}

  

posted @ 2021-08-20 15:51  trump2  阅读(199)  评论(0)    收藏  举报