springboot【二】 统一异常返回、自定义异常

1.公共异常

package com.example.demo.exception;

import com.example.demo.response.Response;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Response<String> handleException(Exception e) {
        return Response.error(e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Response<String> handleBusinessException(BusinessException e) {
        return Response.error(e.getCode(),e.getMessage());
    }
}


2.自定义异常

package com.example.demo.exception;

import lombok.Data;

@Data
public class BusinessException extends RuntimeException{

    private String message;
    private int code;
    public BusinessException(String message, int code) {
        this.message = message;
        this.code = code;
    }
    public BusinessException(String message) {
        this.message = message;
        this.code = 500;
    }
}



打赏

看恩吧
网站不承担任何有关评论的责任
  • 最新评论
  • 总共条评论
取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦