自定义异常

SpringBoot中的自定义异常处理与JSON响应

1.自定义异常类 继承RuntimeException

public class CustomException extends RuntimeException {

    private final String msg;

    public CustomException(String message) {
        super(message);
        this.msg = message;
    }

    public String getMessage() {
        return msg;
    }
}

2.创建一个全局异常处理类GlobalExceptionHandler,在里面处理我们抛出的异常处理。(可自定义异常处理)

import com.ropz.demo.config.ResponseResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice//这个注解标记的类都表示全局异常处理类,并返回json数据格式
public class GlobalExceptionHandler {

    @ExceptionHandler(value = CustomException.class)
    public ResponseResult businessException(CustomException customException){
        return ResponseResult.error(customException.getMessage(),500,null);
    }
}

3.自定义封装的结果集ResponseResult类

import lombok.Data;

@Data
public class ResponseResult{

    private String msg;

    private int code;

    private Object data;

    public ResponseResult(String msg, int code, Object data){
        this.msg = msg;
        this.code = code;
        this.data = data;
    }

    public static ResponseResult success(String msg, int code, Object data) {
        return new ResponseResult(msg, code, data);
    }

    public static ResponseResult error(String msg, int code, Object data) {
        return new ResponseResult(msg, code, data);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值