springboot统一异常处理

时间:2020-05-27
本文章向大家介绍springboot统一异常处理,主要包括springboot统一异常处理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

关于异常,参见:
Java异常

没有异常处理

controller中测试类:

 @GetMapping("/testException")
    public Integer testException(Integer a,Integer b) {
        return a+b;
    }

测试:

如果参数a和b中有一个为空,则会报空指针异常:

浏览器页面长这样:

全局统一异常处理

添加全局统一异常处理类:

package com.example.conf;

import org.springframework.http.HttpStatus;
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;

/**
 * @author liuyj
 * @Title: ControllerHandler 自定义处理异常
 * @create 2020-05-14 10:45
 * @ProjectName test
 * @Description: TODO
 */
@ControllerAdvice
public class ControllerHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResultInfo handleException(Exception ex){
        System.out.println("程序异常:"+ex.toString());
        return new ResultInfo(5000,"请求失败");
    }
}

再次测试:

自定义异常处理

添加异常UserNotExistException类:

public class UserNotExistException extends Exception{
    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public UserNotExistException(Integer id){
        this.id=id;
    }
    @Override
    public String toString() {
        return "用户不存在";
    }
}

controller抛出异常:

  @PostMapping("/getUser")
    public boolean getUser() throws UserNotExistException {
        throw new UserNotExistException(10);
    }

先测试,我们只是抛出异常,并没有对异常进行处理:

添加异常处理:

package com.example.conf;

import org.springframework.http.HttpStatus;
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;

/**
 * @author liuyj
 * @Title: ControllerHandler 自定义处理异常
 * @create 2020-05-14 10:45
 * @ProjectName test
 * @Description: TODO
 */
@ControllerAdvice
public class ControllerHandler {

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResultInfo handleException(Exception ex){
        System.out.println("程序异常:"+ex.toString());
        return new ResultInfo(5000,"请求失败");
    }

    /**
     * 处理UserNotExistException异常
     */
    @ExceptionHandler({UserNotExistException.class})
    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    public ResultInfo handleUserNotExistException(UserNotExistException ex) {
        System.out.println("请求用户数据异常:" + ex.toString());
        return new ResultInfo(5000, "请求用户数据失败");
    }
}

测试:

可以看到已经处理。
测试之前的空指针异常,也没问题

被要求单独处理的异常会先被处理,而后其他异常会被Exception(默认形式)的处理方法捕获。

原文地址:https://www.cnblogs.com/liuyj-top/p/12976448.html