Spring Boot 自定义应用开发框架二—— 异常统一处理

126 阅读1分钟

接上一篇继续搭建项目,项目中的肯定有需要处理异常的地方,而再前后端分离的项目中,要将后台返回的数据统一格式提供给前端,前端才好统一处理信息,那么异常的处理也就必须统一。

Spring boot 统一处理异常非常方便,只要通过注解@RestControllerAdvice 即可,就以上一篇更新信息的异常为例:

一、定义一个异常处理类 

public class HnException extends RuntimeException {

	private static final long serialVersionUID = 4249136427541564896L;
	Logger logger = LoggerFactory.getLogger(this.getClass());
	private String code;

	public HnException(final String code) {
		super(code);
		this.code = code;
		this.logger.error("异常错误:" + this.code);
	}

	public HnException(final String code, final Throwable t) {
		super(code, t);
		this.code = code + " : " + t.getMessage() + " : " + t.getStackTrace()[0];
		this.logger.error("异常错误:" + this.code);
	}

	public HnException(final Throwable t) {
		super(t);
		this.code = t.getMessage() + " : " + t.getStackTrace()[0];
		this.logger.error("异常错误:" + this.code);
	}

	public String getCode() {
		return this.code;
	}

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

二、定义一个全局异常处理类(类似拦截器)

@RestControllerAdvice
public class HnExceptionAdvice {

	@ExceptionHandler(HnException.class)
	public AjaxResponse hnRuntimeException(final HnException exception) {
		return new ErrorResponse(exception.getCode());
	}
}

三、修改update的异常处理代码

    @PostMapping("update")
	public AjaxResponse update(final String name) {
		try {
			System.out.println(1 / 0 + "修改一条数据姓名为:" + name);
		} catch (final Exception e) {
			e.printStackTrace();
			throw new HnException("修改数据异常:" + e.getMessage());
		}
		return new SucceedResponse();
	}

重启项目后运行结果如下,说明已经全局异常处理起作用了

PS:如果按照上面步骤,全局异常不起作用,检查启动类中是否将异常处理类的路径包含。

本文已参与「新人创作礼」活动,一起开启掘金创作之路。