Use spring global exception handler class annotation & @ExceptionHandler

  1. @RestControllerAdvice or by using a uniform exception handling @ControllerAdvice defined classes, rather than each individually defined in the Controller;
  2. @Restcontrolleradvice: Returns json format data;
  3. @ControllerAdvice: Back view type data;
  4. @ResponseBody: and the controller uses the same method, the return value will be transferred json method back to the client;
  5. @ExceptionHandler: used to define the type of exception for the function, and finally Exception object URL is mapped to request return result; exception class for annotation, value attribute specifies the type of exception need intercepted.
  6. After starting the application, is @ ExceptionHandler, @ InitBinder, @ ModelAttribute annotated method will be applied to the method @RequestMapping annotations.
  7. Principle of the global catch exceptions: the use of AOP technology section.
  8. With @RequestBody, solved JSon automatically bound.
  • Because the global exception capture technique using AOP aspects need to import jar package aop
<dependency>
	  <groupId>org.springframework.boot</groupId>
	  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • Define global exception class or sub-packet in the packet's class is started
import com.terse.develop.utils.exception.AdminException;
import com.terse.develop.utils.exception.MsgResultException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.net.ConnectException;
import java.util.List;
import java.util.Set;

/**
 * 全局异常处理
 */
@RestControllerAdvice
@ResponseBody
public class ExceptionHandlerController {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController1.class);

    public static void print(Exception ex) {
        logger.error(ex.toString());
        ex.printStackTrace();
    }

    //Http请求方式不支持
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Exception HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        print(e);
        return new Exception("Http请求方式不支持");
    }

	/**
     * MsgResultException、AdminException 均为自定义异常类
     */
    @ExceptionHandler(value = {MsgResultException.class, AdminException.class})
    public Exception exception(Exception e) {
        print(e);
        if (e instanceof MsgResultException)
            //捕获什么异常信息就返回给前端什么信息
            return new MsgResultException(((MsgResultException) e).getMsg());
        else
            //只返回给后端"请重试"
            return new AdminException("请重试");
    }

    //request Body 读取异常
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public Exception httpMessageNotReadableException(HttpMessageNotReadableException e) {
        print(e);
        return new Exception("请检查数据是否正确");
    }

    //参数类型转换异常
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public Exception getNumberException(MethodArgumentTypeMismatchException e) {
        print(e);
        return new Exception("String类型不能转换成数字类型");
    }

    /**
     * 校验基本类型
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Exception ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        String msg = null;
        for (ConstraintViolation<?> cvl : constraintViolations) {
            msg = cvl.getMessageTemplate();
        }
        logger.error(msg);
        return new Exception(msg);
    }

    //缺少参数异常
    @ExceptionHandler(value = ServletRequestBindingException.class)
    public Exception ServletRequestBindingException(ServletRequestBindingException e) {
        print(e);
        return new Exception("缺少参数");
    }

    /**
     * 校验对象类型
     */
    @ExceptionHandler(value = BindException.class)
    public Exception BindExceptionHandler(BindException bindException) {
        List<FieldError> fieldErrors = bindException.getFieldErrors();
        String msg = null;
        for (FieldError fieldError : fieldErrors) {
            msg = fieldError.getDefaultMessage();
        }
        return new Exception(msg);
    }

    //请求异常
    @ExceptionHandler(value = ConnectException.class)
    public Exception connectException(ConnectException e) {
        print(e);
        return new Exception("服务器异常,请联系管理员");
    }

    //IO流异常
    @ExceptionHandler(value = IOException.class)
    public Exception ioException(IOException e) {
        e.printStackTrace();
        return new Exception("IO流处理异常,请联系管理员");
    }

}

Published 51 original articles · won praise 11 · views 6078

Guess you like

Origin blog.csdn.net/weixin_42140261/article/details/104860568