springboot项目创建笔记14 之《全局异常处理》

一、全局异常处理器
1、不用强制写try...catch,由全局异常处理器统一捕获处理
2、捕获自定义异常
3、Validator参数校验器,参数校验不通过会抛异常,无法通过try...catch语句捕获

二、添加自定义异常
1、建立包com.example.exception
2、添加错误码接口ErrorCode.java

package com.example.exception;

public interface ErrorCode {

	public String code();

    public String msg();

}

3、添加实现了错误码接口的枚举类BizErrorCode.java

package com.example.exception;

import java.text.MessageFormat;

public enum BizErrorCode implements ErrorCode {

	E000000("000000", "成功"), 
	E999998("999998", "请求过于频繁"), 
	E999999("999999", "失败");

	private String code;
	private String msg;

	BizErrorCode(String code, String msg) {
		this.code = code;
		this.msg = msg;
	}

	public static BizErrorCode getErrorCode(int code) {
		BizErrorCode[] var1 = values();
		int var2 = var1.length;

		for (int var3 = 0; var3 < var2; ++var3) {
			BizErrorCode ele = var1[var3];
			if (ele.code().equals(code)) {
				return ele;
			}
		}

		return null;
	}

	/**
	 * get msg
	 *
	 * @return
	 */
	@Override
	public String msg() {
		return msg;
	}

	/**
	 * get code
	 *
	 * @return
	 */
	@Override
	public String code() {
		return code;
	}

	public String msg(Object... args) {
		return MessageFormat.format(this.msg(), args);
	}
}

4、添加自定义异常BizException.java

package com.example.exception;

import java.text.MessageFormat;

public class BizException extends RuntimeException {

	private static final long serialVersionUID = -4032733694182140456L;

	/**
	 * 异常码
	 */
	private String code;
	private Object obj;

	public BizException() {
	}

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

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

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

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

	public BizException(String code, String msgFormat, Object... args) {
		super(MessageFormat.format(msgFormat, args));
		this.code = code;
	}

	public BizException(Boolean isResult, String code, String msgFormat, Object obj, String... args) {
		super(MessageFormat.format(msgFormat, (Object) args));
		this.code = code;
		this.obj = obj;
	}

	public BizException(ErrorCode errorCode, Object... args) {
		super(MessageFormat.format(errorCode.msg(), args));
		this.code = errorCode.code();
	}

	public String getCode() {
		return code;
	}

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

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}
}

三、添加全局异常处理器
1、在包com.example.utils下添加GlobalExceptionHandler.java

package com.example.utils;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.example.exception.BizException;
import com.example.message.CommonResponse;

@ControllerAdvice(basePackages = "com.example.web")
@ResponseBody
public class GlobalExceptionHandler {

	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ExceptionHandler(RuntimeException.class)
	public CommonResponse runtimeException(RuntimeException e) {
		return CommonResponse.fail("999999", e.getMessage());
	}
	
	@ExceptionHandler(Exception.class)
	public CommonResponse exception(Exception e) {
		return CommonResponse.fail("999999", e.getMessage());
	}
	
	@ExceptionHandler(BizException.class)
	public CommonResponse bizException(BizException e) {
		return CommonResponse.fail(e.getCode(), e.getMessage());
	}
}

2、在包com.example.web下添加测试Controller,ExceptionController.java

package com.example.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.exception.BizErrorCode;
import com.example.exception.BizException;

import io.swagger.annotations.Api;

@Api(description = "返回异常测试")
@RestController
@RequestMapping("/error")
public class ExceptionController {

	@GetMapping("/runtimeException")
	public void runtimeException() {
		int i = 9/0;
	}
	
	@GetMapping("/exception")
	public void exception() throws Exception {
		throw new Exception("非法数据");
	}
	
	@GetMapping("/bizException")
	public void bizException() {
		throw new BizException(BizErrorCode.E999998);
	}
}

四、说明
1、@ExceptionHandler注解:指定处理某一类异常
2、@ResponseStatus注解:指定客户端收到的http状态码

五、测试
1、执行/error/bizException

{
  "data": null,
  "sign": null,
  "repCode": "999998",
  "repMsg": "请求过于频繁"
}

2、执行/error/exception

{
  "data": null,
  "sign": null,
  "repCode": "999999",
  "repMsg": "非法数据"
}

3、执行/error/runtimeException

{
  "data": null,
  "sign": null,
  "repCode": "999999",
  "repMsg": "/ by zero"
}

六、组件执行流程
listener --> filter --> 核心servlet --> interceptor --> ControllerAdvice --> aspect --> controller

注:最新代码上传至https://github.com/csj50/myboot
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值