Spring verification annotation exception unified processing class

Keywords: Programming Lombok Mybatis

@ControllerAdvice

This annotation is the core of unified exception handling

Is an Advice that acts on the control layer. This annotation can collect common @ ExceptionHandler, @ InitBinder and @ ModelAttributes methods into one type and apply to all controllers

Design ideas in this category:

  • Use the @ ExceptionHandler annotation to catch the specified or customized exception;

  • Use @ controlleradvise to integrate the method of @ ExceptionHandler into a class;

  • A general exception capture method must be defined to capture undefined exception information;

  • Define an exception class to catch exceptions for the project or business;

  • The abnormal object information is added to the unified result enumeration;

 

Custom global exception class

import com.example.demo.util.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Global exception handling class
 */
@ControllerAdvice
public class CommonExceptionHandler {

    /**
     * General exception handling
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception ex) {
        //Output exception information
        ex.printStackTrace();
        //Handling exception information of verification annotation
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException mex = (MethodArgumentNotValidException) ex;
            return R.failed(mex.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
        } else {
            return R.failed(ex.getMessage());
        }
    }

    /**
     * Handle an exception separately
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e) {
        //Output exception information
        e.printStackTrace();
        return R.failed("Null pointer exception");
    }
}

This is the main core code.

 

Code example

1. Project directory:

 

2.Controller code:

import com.example.demo.model.User;
import com.example.demo.util.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * User login controller
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    /**
     * User login
     * @param user
     * @return
     */
    @PostMapping(value = "/login")
    public R login(@Valid @RequestBody User user){
        System.out.println("Login succeeded!");
        return R.ok(user);
    }

}

 

3.User entity class

import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

/**
 * User login entity class
 */
@Data
public class User {

    @NotBlank(message = "User name cannot be empty")
    private String username;

    @NotBlank(message = "Password cannot be empty")
    @Size(max = 20, min = 6, message = "Password length is 6-20 Between characters")
    private String password;

}

The code of API code enumeration and R return object will not be shown. These two codes refer to the design of R object in mybatis plus. They are relatively simple and can be written at will.

 

PostMan request test

Seeing this result, our global unified handling of annotation verification exception is successful.

Posted by niekos on Tue, 05 May 2020 12:04:34 -0700