SpringBoot第十一课——统一异常处理

关于异常的概念什么的这里就不多说了(详见:https://www.cnblogs.com/williamjie/p/9103658.html),我们来直接看在SpringBoot中怎么统一处理异常吧。

1.创建统一处理异常的类


@ControllerAdvice
public class MyExcepthonHandler {

	@ResponseBody
	@ExceptionHandler(value = MyException.class)
	public Result handlerException1(MyException exception) {
		ErrorEnum errEnum = exception.getErrEnum();
		Result res= new Result();
		res.setData("啥也没有");
		res.setErrCode(errEnum.SEVICE_ERROR.getErrCode());
		res.setErrMsg(errEnum.SEVICE_ERROR.getErrMsg());
		return res;
	}
}

@ControllerAdvice指定了controller的拦截切面类,@ExceptionHandler(value = MyException.class)表示我们要拦截 的异常类型。MyException是我们自定义的异常,如下:

2.自定义异常类:

public class MyException extends RuntimeException{
	private ErrorEnum errEnum;
	
	public MyException(ErrorEnum errEnum) {
		this.errEnum = errEnum;
	}
	
	public ErrorEnum getErrEnum() {
		return this.errEnum;
	}
	/**
	 * @author xuyp
	 * 错误类型的枚举
	 */
	public enum ErrorEnum {
		
		SEVICE_ERROR(1001,"业务类型异常"),
		
		SYSTEM_ERROR(1002,"系统异常");
		
		ErrorEnum(int code, String errMsg){
			this.errCode = code;
			this.errMsg = errMsg;
		}
		private int errCode;
		private String errMsg;
		public int getErrCode() {
			return errCode;
		}
		public String getErrMsg() {
			return errMsg;
		}
	}
}

上面我们异常处理的方法返回的是Result ,@ResponseBody使最终会以json 的方式返回前端

 Result

public class Result {
	
	private Object data;
	private int errCode;
	private String errMsg;
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}
	public int getErrCode() {
		return errCode;
	}
	public void setErrCode(int errCode) {
		this.errCode = errCode;
	}
	public String getErrMsg() {
		return errMsg;
	}
	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}
}

3.抛出异常的Controller:

@RestController
public class Controller1 {

	@RequestMapping("/do")
	public String doSomething() {
		System.out.println("###doSomething");
		if(1 < 2) {
			throw new MyException(ErrorEnum.SEVICE_ERROR);
		}
		return "do something";
	}
}

启动服务,来验证一下:

 SpringBoot第十一课——统一异常处理_第1张图片

如图,成功拦截到了异常!

 

你可能感兴趣的:(javaWeb)