preface

It is also very important to capture, throw and record exceptions in project development, which is convenient for us to locate and track bugs in future projects.

Hibernate Validator parameter verification

Global parameter validation is performed by integrating spring-boot-starter-validation

  <! -- Parameter verification -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
Copy the code

Please refer to my two articles for specific use

SpringBoot Validation provides elegant Validation of global parameters

SpringBoot Validation details auto-validation and grouping Validation

Global exception catch GlobalExceptionHandler

package cn.soboys.core;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.soboys.core.authentication.AuthenticationException;
import cn.soboys.core.ret.Result;
import cn.soboys.core.ret.ResultCode;
import cn.soboys.core.ret.ResultResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/17 20:19 * Unified handling of global exceptions */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /** * Handle the exception thrown when the json request body calls the interface object parameter verification failure */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result jsonParamsException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List errorList = CollectionUtil.newArrayList();

        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String msg = String.format("% s % s.", fieldError.getField(), fieldError.getDefaultMessage());
            errorList.add(msg);
        }
        return ResultResponse.failure(ResultCode.PARAMS_IS_INVALID, errorList);
    }


    /** * Handle the exception thrown by a single parameter validation failure */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result ParamsException(ConstraintViolationException e) { List errorList = CollectionUtil.newArrayList(); Set<ConstraintViolation<? >> violations = e.getConstraintViolations();for(ConstraintViolation<? > violation : violations) { StringBuilder message =new StringBuilder();
            Path path = violation.getPropertyPath();
            String[] pathArr = StrUtil.splitToArray(path.toString(), ".");
            String msg = message.append(pathArr[1]).append(violation.getMessage()).toString();
            errorList.add(msg);
        }
        return ResultResponse.failure(ResultCode.PARAMS_IS_INVALID, errorList);
    }

    / * * *@param e
     * @returnHandle the exception */ thrown when the form data method fails to call the interface object parameter verification
    @ExceptionHandler(BindException.class)
    public Result formDaraParamsException(BindException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getField() + o.getDefaultMessage())
                .collect(Collectors.toList());
        return ResultResponse.failure(ResultCode.PARAMS_IS_INVALID, collect);
    }

    /** * The request method is not allowed to exception */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return ResultResponse.failure(ResultCode.METHOD_NOT_ALLOWED);
    }

    / * * *@param e
     * @returnContent-type /Accept * application/json * application/ x-w-form-urlencoded */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result httpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        return ResultResponse.failure(ResultCode.BAD_REQUEST);
    }

    /** * The handlerMapping interface does not run abnormally **@param e
     * @return* /
    @ExceptionHandler(NoHandlerFoundException.class)
    public Result noHandlerFoundException(NoHandlerFoundException e) {
        return ResultResponse.failure(ResultCode.NOT_FOUND, e.getMessage());
    }


    /** * Authentication exception *@param e
     * @return* /
    @ExceptionHandler(AuthenticationException.class)
    public Result UnNoException(AuthenticationException e) {
        return ResultResponse.failure(ResultCode.UNAUTHORIZED,e.getMessage());
    }

    / * * * *@paramE Unknown exception capture *@return* /
    @ExceptionHandler(Exception.class)
    public Result UnNoException(Exception e) {
        returnResultResponse.failure(ResultCode.INTERNAL_SERVER_ERROR, e.getMessage()); }}Copy the code

See my article for more details on SpringBoot’s elegant global exception handling