Springboot系列——统一异常处理(可配置返回json格式)

Springboot系列——统一异常处理(可配置返回json格式)

今天说一下如何在SpringBoot实现全局异常机制,在没有用springboot大家要实现这一的功能基本上都是通过aop的思想,而现在springboot中对它要进行了一次封装,开发者使用起来更加的简单

1.博主建好统一异常处理后,只是建了一个简单的测试,大家可以结合自己的项目进行测试

Springboot系列——统一异常处理(可配置返回json格式)_第1张图片2.在pom文件中加入依赖

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

    
    
        UTF-8
        UTF-8
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter
        

        
        
            io.springfox
            springfox-swagger2
            2.5.0
        
        
        
        
            io.springfox
            springfox-swagger-ui
            2.5.0
        
                
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
        
            junit
            junit
        
                
        
        
            org.projectlombok
            lombok
            true
        
        
        
        
            com.alibaba
            fastjson
            1.2.46
        
        
        
            org.springframework.boot
            spring-boot-devtools
        

        
        
            org.quartz-scheduler
            quartz
            2.3.0
        

        
        
            org.apache.poi
            poi
            3.17
        

        
            org.apache.poi
            poi-ooxml
            RELEASE
        
        
        
            org.projectlombok
            lombok
            1.18.8
        

    

    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
        
        SpringBoot-one
    



3.定义一个封装json的工具类,使用阿里巴巴的fastjson

/**
 * @author 倾宸
 * @date 2019/6/24 16:13
 */

@Setter
@Getter
@ToString
public class JsonResult implements Serializable{

    private int code;   //返回码 非0即失败
    private String msg; //消息提示
    private Map data; //返回的数据

    public JsonResult(){

    };

    public JsonResult(int code, String msg, Map data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static String success() {
        return success(new HashMap(0));
    }
    public static String success(Map data) {
        return JSON.toJSONString(new JsonResult(0, "解析成功", data));
    }

    public static String failed() {
        return failed("解析失败");
    }
    public static String failed(String msg) {
        return failed(-1, msg);
    }
    public static String failed(int code, String msg) {
        return  JSON.toJSONString(new JsonResult(code, msg, new HashMap(0)));
    }
    }

4.设定全局变量异常处理

/**
 * @author 倾宸
 * @date 2019/6/24 16:30
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {


    private static final String logExceptionFormat = "Capture Exception By GlobalExceptionHandler: Code: %s Detail: %s";
    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //运行时异常
    @ExceptionHandler(RuntimeException.class)
    public String runtimeExceptionHandler(RuntimeException ex) {
        return resultFormat(1, ex);
    }

    //空指针异常
    @ExceptionHandler(NullPointerException.class)
    public String nullPointerExceptionHandler(NullPointerException ex) {
        System.err.println("NullPointerException:");
        return resultFormat(2, ex);
    }

    //类型转换异常
    @ExceptionHandler(ClassCastException.class)
    public String classCastExceptionHandler(ClassCastException ex) {
        return resultFormat(3, ex);
    }

    //IO异常
    @ExceptionHandler(IOException.class)
    public String iOExceptionHandler(IOException ex) {
        return resultFormat(4, ex);
    }

    //未知方法异常
    @ExceptionHandler(NoSuchMethodException.class)
    public String noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        return resultFormat(5, ex);
    }

    //数组越界异常
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public String indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        return resultFormat(6, ex);
    }

    //400错误
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public String requestNotReadable(HttpMessageNotReadableException ex) {
        System.out.println("400..requestNotReadable");
        return resultFormat(7, ex);
    }

    //400错误
    @ExceptionHandler({TypeMismatchException.class})
    public String requestTypeMismatch(TypeMismatchException ex) {
        System.out.println("400..TypeMismatchException");
        return resultFormat(8, ex);
    }

    //400错误
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public String requestMissingServletRequest(MissingServletRequestParameterException ex) {
        System.out.println("400..MissingServletRequest");
        return resultFormat(9, ex);
    }

    //405错误
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public String request405(HttpRequestMethodNotSupportedException ex) {
        return resultFormat(10, ex);
    }

    //406错误
    @ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
    public String request406(HttpMediaTypeNotAcceptableException ex) {
        System.out.println("406...");
        return resultFormat(11, ex);
    }

    //500错误
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public String server500(RuntimeException ex) {
        System.out.println("500...");
        return resultFormat(12, ex);
    }

    //栈溢出
    @ExceptionHandler({StackOverflowError.class})
    public String requestStackOverflow(StackOverflowError ex) {
        return resultFormat(13, ex);
    }

    //除数不能为0
    @ExceptionHandler({ArithmeticException.class})
    public String arithmeticException(ArithmeticException ex) {
        return resultFormat(13, ex);
    }


    //其他错误
    @ExceptionHandler({Exception.class})
    public String exception(Exception ex) {
        return resultFormat(14, ex);
    }

    private  String resultFormat(Integer code, T ex) {
        ex.printStackTrace();
        log.error(String.format(logExceptionFormat, code, ex.getMessage()));
        return JsonResult.failed(code, ex.getMessage());
    }

}

5.测试Controller

package com.gg.Controller;

import com.gg.Exception.GlobalExceptionHandler;
import com.gg.Tool.JsonResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 倾宸
 * @date 2019/6/24 16:33
 */
@RestController
@RequestMapping("w")
public class ExceptionController {

    @ApiOperation(value = "测试", notes = "测试")
    @ApiImplicitParam(name = "user", value = "用户进行测试", required = true,dataType = "user")
    @RequestMapping("/exce")
    public Object showInfo(){
        System.err.println("dddddddddddddd");
        String info ="你好";
        int a = 1/0;
        return info;
    }

}

6.编写启动类进行测试

/**
 * @author 倾宸
 * @date 2019/6/19 9:24
 */
@SpringBootApplication
public class  SpringBootOApplication{

    /**
     * @Author LiuSenChuan
     * @Description 启动类
     * @Date  2019/6/19
     * @Param
     * @return
     **/
    public static void main(String[] args) {
        SpringApplication.run(SpringBootOApplication.class, args);
    }
}

7.运行结果
Springboot系列——统一异常处理(可配置返回json格式)_第2张图片8.对个别新注解的解释

过使⽤ @ControllerAdvice 定义统⼀的异常处理类,⽽不是在每个
Controller中逐个定义。
@ExceptionHandler ⽤来定义函数针对的异常类型

最后

更多参考精彩博文请看这里:陈永佳的博客
喜欢博主的小伙伴可以加个关注、点个赞哦,持续更新嘿嘿!***

你可能感兴趣的:(Java基础系列,编程工具系列)