SpringBoot——全局异常处理和自定义异常

  • Post author:
  • Post category:其他


SpringBoot中有一个

@ControllerAdvice

的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用

@ExceptionHandler

注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。

@ControllerAdvice
public class GlobalException {

    @ExceptionHandler(value =Exception.class)
	public String exceptionHandler(Exception e){
		System.out.println("未知异常!原因是:"+e);
       	return e.getMessage();
    }
}

上述的示例中,我们对捕获的异常进行简单的二次处理,返回异常的信息,虽然这种能够让我们知道异常的原因,但是在很多的情况下来说,可能还是不够人性化,不符合我们的要求。

那么我们这里可以通过自定义的异常类以及枚举类来实现我们想要的那种数据吧。



一、自定义基础接口类

首先定义一个基础的接口类,自定义的错误描述枚举类需实现该接口。

public interface BaseErrorInfo {
    /** 错误码*/
    String getResultCode();

    /** 错误描述*/
    String getResultMsg();
}



二、自定义枚举类

枚举类实现接口,枚举类要有构造方法,不然自定义错误信息报错


import com.example.mybatis.demo.exception.BaseErrorInfo;

public enum CommonNum implements BaseErrorInfo {
    /**
     * 自定义错误信息
     */
    SUCCESS("200", "成功!"),
    BODY_NOT_MATCH("400","请求的数据格式不符!"),
    SIGNATURE_NOT_MATCH("401","请求的数字签名不匹配!"),
    NOT_FOUND("404", "未找到该资源!"),
    INTERNAL_SERVER_ERROR("500", "服务器内部错误!"),
    SERVER_BUSY("503","服务器正忙,请稍后再试!")
    ;
    
    /**
     * 错误码
     */
    private String resultCode;

    /**
     * 错误描述
     */
    private String resultMsg;


    CommonNum(String resultCode, String resultMsg) {
        this.resultCode = resultCode;
        this.resultMsg = resultMsg;
    }


    @Override
    public String getResultCode() {
        return null;
    }

    @Override
    public String getResultMsg() {
        return null;
    }
}



三、自定义异常类

public class ServiceRuntimeException extends RuntimeException{
    /**
     * 错误码
     */
    private String code;
    /**
     * 错误信息
     */
    private String message;

    public ServiceRuntimeException(String message){
        super(message);
        this.message = message;

    }

    public ServiceRuntimeException(String code,String message){
        super(message);
        this.code = code;
        this.message = message;

    }

    //Throwable是Error和Exception的父类,用来定义所有可以作为异常被抛出来的类。
    public ServiceRuntimeException(String code,String message,Throwable cause){
        super(message,cause);
        this.code = code;
        this.message = message;

    }

    public ServiceRuntimeException(BaseErrorInfo baseErrorInfo){
        super(baseErrorInfo.getResultMsg());
        this.code = baseErrorInfo.getResultCode();
        this.message = baseErrorInfo.getResultMsg();
    }

    public ServiceRuntimeException(BaseErrorInfo baseErrorInfo,Throwable cause){
        super(baseErrorInfo.getResultMsg(),cause);
        this.code = baseErrorInfo.getResultCode();
        this.message = baseErrorInfo.getResultMsg();
    }


    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}



四、自定义数据格式

自定义数据传输格式

import com.example.mybatis.demo.exception.BaseErrorInfo;

public class ResultGenerator {
    /**
     * 响应代码
     */
    private String code;

    /**
     * 响应消息
     */
    private String message;

    /**
     * 响应结果
     */
    private Object result;


    public ResultGenerator(){

    }
    public ResultGenerator(BaseErrorInfo baseErrorInfo){
        this.code = baseErrorInfo.getResultCode();
        this.message = baseErrorInfo.getResultMsg();

    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    /**
     * 成功
     * @return
     */
    public static ResultGenerator success(){
        return success(null);
    }

    /**
     * 成功
     * @param data
     * @return
     */
    public static ResultGenerator success(Object data){
        ResultGenerator generator = new ResultGenerator();
        generator.setCode(CommonNum.SUCCESS.getResultCode());
        generator.setMessage(CommonNum.SUCCESS.getResultMsg());
        generator.setResult(data);
        return generator;
    }

    /**
     * 失败
     * @param baseErrorInfo
     * @return
     */
    public static ResultGenerator error(BaseErrorInfo baseErrorInfo){
        ResultGenerator generator = new ResultGenerator();
        generator.setCode(baseErrorInfo.getResultCode());
        generator.setMessage(baseErrorInfo.getResultMsg());
        generator.setResult(null);
        return  generator;

    }

    /**
     * 失败
     * @param code
     * @param message
     * @return
     */
    public static ResultGenerator error(String code,String message){
        ResultGenerator generator = new ResultGenerator();
        generator.setCode(code);
        generator.setMessage(message);
        generator.setResult(null);
        return generator;
    }

    @Override
    public String toString() {
        return "ResultGenerator{" +
                "code='" + code + '\'' +
                ", message='" + message + '\'' +
                ", result=" + result +
                '}';
    }
}



五、自定义全局异常处理类

import com.example.mybatis.demo.common.CommonNum;
import com.example.mybatis.demo.common.ResultGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalException {
    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ServiceRuntimeException.class)
    public ResultGenerator serviceRuntimeException(ServiceRuntimeException e){
        logger.error("发生业务异常!原因是:{}",e.getMessage());
        return ResultGenerator.error(e.getCode(),e.getMessage());

    }

    /**
     * 处理空指针异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = NullPointerException.class)
    public ResultGenerator exceptionHandler(NullPointerException e){
        logger.error("发生空指针异常!原因是:",e);
        return ResultGenerator.error(CommonNum.BODY_NOT_MATCH);

    }

    /**
     * 其它异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultGenerator exceptionHandler(Exception e){
        logger.error("发生空指针异常!原因是:",e);
        return ResultGenerator.error(CommonNum.INTERNAL_SERVER_ERROR);

    }

}



六、测试

因为这里我们只是用于做全局异常处理的功能实现以及测试,所以这里我们只需在添加一个实体类和一个控制层类即可。

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    /** 编号 */
    private int id;
    /** 姓名 */
    private String name;
    /** 年龄 */
    private int age;

    public User(){
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}
import com.example.mybatis.demo.entity.User;
import com.example.mybatis.demo.exception.ServiceRuntimeException;
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;


@RestController
@RequestMapping(value = "/api")
public class UserRestController {

    @PostMapping("/userInsert")
    public boolean insert(@RequestBody User user) {
        System.out.println("开始新增...");
        //如果姓名为空就手动抛出一个自定义的异常!
        if(user.getName()==null){
            throw  new ServiceRuntimeException("-1","用户姓名不能为空!");
        }
        return true;
    }

    @PostMapping("/userUpdate")
    public boolean update(@RequestBody User user) {
        System.out.println("开始更新...");
        //这里故意造成一个空指针的异常,并且不进行处理
        String str=null;
        str.equals("111");
        return true;
    }

    @PostMapping("/userDelete")
    public boolean delete(@RequestBody User user)  {
        System.out.println("开始删除...");
        //这里故意造成一个异常,并且不进行处理
        Integer.parseInt("abc123");
        return true;
    }


}


注意,用

postMan

测试传值的时候要传

json

格式,如图:


在这里插入图片描述



版权声明:本文为weixin_43085797原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。