程序开发过程中各种各样运行时异常,有时是无法预测的,有时是应业务需要的特殊异常
对于不同的异常有时需要特别是处理
异常处理中需要用到的注解
@ExceptionHandler:处理某一类异常
@ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开
@ResponseStatus: 可以指定异常响应的HTTP状态码
一、定义全局异常捕获类
package com.pd.shop.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* 全局异常捕获处理
*
* @author Administrator
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常捕获,捕获类型是:Exception, 除自定义类型外都应该被捕获
*
* @param e
* @return
*/
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
log.info("系统异常:{}", e);
//编写处理异常逻辑
// 建议定义统一的返回数据格式,参考:javascript:void(0)
//return new Result(ResultCodeEnum.NO);
return "{ \"code\" : 0, \"msg\" : \"" + e + "\" }";
}
/**
* 自定义业务异常,捕获类型是:BizException, 只能捕获BizException类型的异常
*
* @param e
* @return
*/
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(BizException.class)
public String handleBizException(BizException e) {
log.info("业务异常:{}", e);
//编写处理异常逻辑
// 建议定义统一的返回数据格式,参考:javascript:void(0)
//return new Result(e.getCode(), e.getMsg());
return "{ \"code\" : " + e.code + ", \"msg\" : \"" + e.msg + "\" }";
}
//可以追加其他自定义异常,类比BizException
}
二、自定义业务异常
package com.pd.shop.exception;
import lombok.Data;
/**
* 自定义的业务异常
*
* @author Administrator
*/
@Data
public class BizException extends RuntimeException {
/**
* 错误码
*/
protected Integer code;
/**
* 错误信息
*/
protected String msg;
public BizException(Integer code, String msg){
this.code = code;
this.msg = msg;
}
}
三、自定义业务异常
package com.pd.shop.controller;
import com.pd.shop.exception.BizException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Administrator
*/
@Api(value = "测试类", tags = "测试类")
@RestController
@RequestMapping("/v1/testApi")
public class TestApiController {
@GetMapping("/exception1")
@ApiOperation(value = "测试exception1", httpMethod = "GET")
public String exception1(){
if(true){
//建议可以定义业务异常枚举: 参考 javascript:void(0)
throw new BizException(3,"错误3");
}
return "OK";
}
@GetMapping("/exception2")
@ApiOperation(value = "测试exception2", httpMethod = "GET")
public String exception2(){
if(true){
Integer A = 1/0;
}
return "OK";
}
}