Spring Boot 菜鸟教程 6 全局异常处理

@ControllerAdvice源码

package org.springframework.web.bind.annotation;

import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Component;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
    
    @AliasFor("basePackages")
    String[] value() default {};    
    @AliasFor("value")
    String[] basePackages() default {};
    Class[] basePackageClasses() default {};
    Class[] assignableTypes() default {};
    Class[] annotations() default {};

}

源码分析

@ ControllerAdvice是一个@ Component,
用于定义@ ExceptionHandler的,@InitBinder和@ModelAttribute方法,适用于所有使用@ RequestMapping方法,并处理所有@ RequestMapping标注方法出现异常的统一处理

项目图片

Spring Boot 菜鸟教程 6 全局异常处理_第1张图片
这里写图片描述

pom.xml


    4.0.0

    com.jege.spring.boot
    spring-boot-controller-advice
    0.0.1-SNAPSHOT
    jar

    spring-boot-controller-advice
    http://maven.apache.org

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.1.RELEASE
        
    

    
        UTF-8
        1.8
    

    

        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        

        
        
            com.h2database
            h2
            runtime
        

        
        
            org.springframework.boot
            spring-boot-starter-test
            
            test
        

    

    
        spring-boot-controller-advice
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    ${java.version}
                    ${java.version}
                
            
        
    


全局异常处理类CommonExceptionAdvice

package com.jege.spring.boot.exception;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.jege.spring.boot.json.AjaxResult;

/**
 * @author JE哥
 * @email [email protected]
 * @description:全局异常处理
 */
@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice {

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

  /**
   * 400 - Bad Request
   */
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(MissingServletRequestParameterException.class)
  public AjaxResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
    logger.error("缺少请求参数", e);
    return new AjaxResult().failure("required_parameter_is_not_present");
  }

  /**
   * 400 - Bad Request
   */
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(HttpMessageNotReadableException.class)
  public AjaxResult handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
    logger.error("参数解析失败", e);
    return new AjaxResult().failure("could_not_read_json");
  }

  /**
   * 400 - Bad Request
   */
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(MethodArgumentNotValidException.class)
  public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    logger.error("参数验证失败", e);
    BindingResult result = e.getBindingResult();
    FieldError error = result.getFieldError();
    String field = error.getField();
    String code = error.getDefaultMessage();
    String message = String.format("%s:%s", field, code);
    return new AjaxResult().failure(message);
  }

  /**
   * 400 - Bad Request
   */
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(BindException.class)
  public AjaxResult handleBindException(BindException e) {
    logger.error("参数绑定失败", e);
    BindingResult result = e.getBindingResult();
    FieldError error = result.getFieldError();
    String field = error.getField();
    String code = error.getDefaultMessage();
    String message = String.format("%s:%s", field, code);
    return new AjaxResult().failure(message);
  }

  /**
   * 400 - Bad Request
   */
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(ConstraintViolationException.class)
  public AjaxResult handleServiceException(ConstraintViolationException e) {
    logger.error("参数验证失败", e);
    Set> violations = e.getConstraintViolations();
    ConstraintViolation violation = violations.iterator().next();
    String message = violation.getMessage();
    return new AjaxResult().failure("parameter:" + message);
  }

  /**
   * 400 - Bad Request
   */
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(ValidationException.class)
  public AjaxResult handleValidationException(ValidationException e) {
    logger.error("参数验证失败", e);
    return new AjaxResult().failure("validation_exception");
  }

  /**
   * 405 - Method Not Allowed
   */
  @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
  @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  public AjaxResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
    logger.error("不支持当前请求方法", e);
    return new AjaxResult().failure("request_method_not_supported");
  }

  /**
   * 415 - Unsupported Media Type
   */
  @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
  @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
  public AjaxResult handleHttpMediaTypeNotSupportedException(Exception e) {
    logger.error("不支持当前媒体类型", e);
    return new AjaxResult().failure("content_type_not_supported");
  }

  /**
   * 500 - Internal Server Error
   */
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ExceptionHandler(ServiceException.class)
  public AjaxResult handleServiceException(ServiceException e) {
    logger.error("业务逻辑异常", e);
    return new AjaxResult().failure("业务逻辑异常:" + e.getMessage());
  }

  /**
   * 500 - Internal Server Error
   */
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ExceptionHandler(Exception.class)
  public AjaxResult handleException(Exception e) {
    logger.error("通用异常", e);
    return new AjaxResult().failure("通用异常:" + e.getMessage());
  }

  /**
   * 操作数据库出现异常:名称重复,外键关联
   */
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  @ExceptionHandler(DataIntegrityViolationException.class)
  public AjaxResult handleException(DataIntegrityViolationException e) {
    logger.error("操作数据库出现异常:", e);
    return new AjaxResult().failure("操作数据库出现异常:字段重复、有外键关联等");
  }
}


自定义异常ServiceException

package com.jege.spring.boot.exception;

/**
 * @author JE哥
 * @email [email protected]
 * @description:自定义异常类
 */
public class ServiceException extends RuntimeException {
  public ServiceException(String msg) {
    super(msg);
  }
}


不需要application.properties##

控制器AdviceController

package com.jege.spring.boot.controller;

import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jege.spring.boot.exception.ServiceException;

/**
 * @author JE哥
 * @email [email protected]
 * @description:全局异常处理演示入口
 */
@RestController
public class AdviceController {

  @RequestMapping("/hello1")
  public String hello1() {
    int i = 1 / 0;
    return "hello";
  }

  @RequestMapping("/hello2")
  public String hello2(Long id) {
    String string = null;
    string.length();
    return "hello";
  }

  @RequestMapping("/hello3")
  public List hello3() {
    throw new ServiceException("test");
  }
}

访问

  • http://localhost:8080/hello1
    {"meta":{"success":false,"message":"通用异常:/ by zero"},"data":null}
  • http://localhost:8080/hello2
    {"meta":{"success":false,"message":"通用异常:null"},"data":null}
  • http://localhost:8080/hello3
    {"meta":{"success":false,"message":"业务逻辑异常:test"},"data":null}

源码地址

https://github.com/je-ge/spring-boot

如果觉得我的文章或者代码对您有帮助,可以请我喝杯咖啡。
**您的支持将鼓励我继续创作!谢谢! **

微信打赏

支付宝打赏

你可能感兴趣的:(Spring Boot 菜鸟教程 6 全局异常处理)