美文网首页
@Valid通用异常处理

@Valid通用异常处理

作者: __简单点__ | 来源:发表于2020-12-17 14:10 被阅读0次

package com.bear.mobile.util;

import com.bear.mobile.ResponseData;

import lombok.extern.slf4j.Slf4j;

import org.springframework.validation.BindException;

import org.springframework.validation.BindingResult;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j

@RestControllerAdvice

public class CommonExceptionHandler {

@ExceptionHandler(BindException.class)

public ResponseDatahandlerBindException(BindException exception) {

return handlerNotValidException(exception);

    }

/**

    * 对方法参数校验异常处理方法(前端提交的方式为json格式出现异常时会被该异常类处理)

    * json格式提交时,spring会采用json数据的数据转换器进行处理(进行参数校验时错误是抛出MethodArgumentNotValidException异常)

    */

    @ExceptionHandler(MethodArgumentNotValidException.class)

public ResponseDatahandlerArgumentNotValidException(MethodArgumentNotValidException exception) {

return handlerNotValidException(exception);

    }

public ResponseDatahandlerNotValidException(Exception e) {

log.debug("begin resolve argument exception");

        BindingResult result;

        if (einstanceof BindException) {

BindException exception = (BindException) e;

            result = exception.getBindingResult();

        }else {

MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;

            result = exception.getBindingResult();

        }

StringBuilder stringBuilder =new StringBuilder();

        if (result.hasErrors()) {

List fieldErrors = result.getFieldErrors();

            fieldErrors.forEach(error -> {

//                stringBuilder.append(error.getField()+":");

                stringBuilder.append(error.getDefaultMessage()+" ");

            });

        }

log.error("传递参数异常:"+stringBuilder.toString());

        return ResponseData.error(stringBuilder.toString());

    }

}

相关文章

网友评论

      本文标题:@Valid通用异常处理

      本文链接:https://www.haomeiwen.com/subject/guumwktx.html