springboot 自定义异常,并捕获异常返给前端

背景

在开发中,如果用try catch的方式,每个方法都需要单独实现,为了方便分类异常,返回给前端,采用了@ControllerAdvice注解和继承了RuntimeException的方式来实现。


实现内容

捕获了三类异常
1.业务异常

          BusinessException

2.系统异常 

        SystemException

3.其他异常

        利用@ExceptionHandler(RuntimeException.class)去捕获

ExceptionAdvice类捕获以上三类异常,并返回自定义类型格式数据

实现代码

业务异常BusinessException类实现方式,继承RuntimeException

public class BusinessException extends  RuntimeException {
	/**
	 * 错误编码
	 */
	private String code;

	public BusinessException() {
		super();
	}

	public BusinessException(String message) {
		super(message);
	}

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

	public BusinessException(Throwable cause) {
		super(cause);
	}

	public BusinessException(String message, Throwable cause) {
		super(message, cause);
	}

	public BusinessException(String message, Throwable cause,
							 boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public String getCode() {
		return code;
	}

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

	@Override
	public String getMessage() {
		return super.getMessage();
	}

	@Override
	public String toString() {
		return this.code + ":" + this.getMessage();
	}
}

系统异常SystemException类实现方式,继承RuntimeException,同业务异常类的实现方式一样

public class SystemException extends  RuntimeException {
	/**
	 * 错误编码
	 */
	private String code;

	public SystemException() {
		super();
	}

	public SystemException(String message) {
		super(message);
	}

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

	public SystemException(Throwable cause) {
		super(cause);
	}

	public SystemException(String message, Throwable cause) {
		super(message, cause);
	}

	public SystemException(String message, Throwable cause,
                           boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}

	public String getCode() {
		return code;
	}

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

	@Override
	public String getMessage() {
		return super.getMessage();
	}

	@Override
	public String toString() {
		return this.code + ":" + this.getMessage();
	}
}

ExceptionAdvice类,采用增强Controller注解 @ControllerAdvice的方式来实现

1.方法名称和返回类型都可以根据自己需要定义

2.采用注解@ExceptionHandler,就是捕获的异常类型,我们只需要把需要捕获异常类型写进来就好

 ExceptionAdvice 具体代码实现如下:

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 ExceptionAdvice {
    public static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ResponseBody
    @ExceptionHandler(SystemException.class)
    public Result handleException(Exception e) {
        logger.error("系统异常信息:", e);
        Result result = new Result();
        if (e instanceof BusinessException) {
            e = (BusinessException) e;
            result.setCode(((BusinessException) e).getCode());
        }
        result.setFailed(e.getMessage());
        return result;
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result handleException(RuntimeException e) {
        logger.error("异常信息:", e.getMessage());
        Result result = new Result();
        result.setStatus(500);
        result.setMessage(e.getMessage());
        return result;
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AjaxJson doBusinessException(Exception e) {
        AjaxJson ajaxJson = new AjaxJson();
        logger.error("业务异常消息:", e.getMessage());
        ajaxJson.setRet(-1);
        ajaxJson.setMsg(e.getMessage());
        return ajaxJson;
    }

}

测试代码

1.我们捕获一个业务异常BusinessException,输出aaa

 

2.捕获系统异常

throw new SystemException("aaaa");

3.其他的try catch的异常,这个就可以捕获了 

 

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SpringBoot中,我们可以通过自定义异常来处理业务逻辑中出现的异常情况。以下是实现步骤: 1. 自定义异常类 在项目包中创建一个自定义的异常类,需要继承Exception或RuntimeException。 ``` public class CustomException extends RuntimeException { private int code; private String message; public CustomException(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } } ``` 2. 异常处理类 在项目包中创建一个异常处理类,需要使用@ControllerAdvice和@ExceptionHandler注解,通过指定异常类来捕获异常并处理。 ``` @ControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(CustomException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result handleCustomException(CustomException e) { return new Result(e.getCode(), e.getMessage(), null); } } ``` 3. 统一响应对象 在项目包中创建一个统一响应对象类,用于统一封装响应信息。 ``` public class Result<T> { private int code; private String message; private T data; public Result(int code, String message, T data) { this.code = code; this.message = message; this.data = data; } public int getCode() { return code; } public String getMessage() { return message; } public T getData() { return data; } } ``` 以上就是springboot自定义异常的实现步骤。在业务逻辑中抛出自定义异常即可触发异常处理类中的处理方法,并返回统一响应对象。这样可以统一处理异常并返回规范化的响应信息,方便前端或其他系统的处理。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值