ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-08-20 16:04:22  阅读:198  来源: 互联网

标签:web JsonResult 捕获 springframework Valid org import 全局 class


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;

标签:web,JsonResult,捕获,springframework,Valid,org,import,全局,class
来源: https://www.cnblogs.com/trump2/p/15166793.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有