一个前端请求过来,后端执行相关业务逻辑时通常需要做许多校验判断,当数据正常且符合要求时才能执行相关操作。在校验的过程中,如果发现不校验不通过,需要返回前端相关的校验失败信息展示给用户。如果是自己写到返回值里的话太麻烦,直接抛出异常使接口500又不太符合逻辑,毕竟只是业务校验失败。
通常我们的做法是自定义一个业务异常,然后抛出这个自定义异常,在接口返回前对异常进行捕获处理。这样一来,接口返回状态是200,错误信息也带给了前端,也不需要我们自己一个个慢慢设置返回的值。
先看demo,再细说
创建一个自定义异常类
import lombok.Data;
/**
* @author: tanghaizhi
* @CreateTime: 2022/5/10 16:30
* @Description:
*/
@Data
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();
}
}
对异常进行统一处理
import com.act.able.common.entity.R;
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.RestController;
import java.util.Map;
/**
* @author: tanghaizhi
* @CreateTime: 2022/5/10 16:31
* @Description:
*/
@RestController
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler(BusinessException.class)
@ResponseBody
public R<Map<String,Object>> doBusinessException(Exception e) {
R<Map<String,Object>> result = new R<Map<String,Object>>();
result.setCode(500);
result.setMsg("业务异常:"+e.getMessage());
return result;
}
}
这里解释一下R<Map<String,Object>>这个对象,这个对象是我们系统中的统一返回值。有code,msg,data三个属性。其中data为泛型,可在new时进行指定,一般用来存放反给前端的列表数据等。
code表示接口功能执行成功还是失败等,不同code含义不同,看团队内部如何定义。msg为携带的返回信息,通常业务异常等报错信息都放在这里带回给前端。
做完上面的准备工作后就可以开始进行测试了
@RequestMapping(value = "/selectTest")
public R<?> selectTest(String str){
return new R<>(codeConversionService.selectTest(str),R.SUCCESS);
}
public String selectTest(String str){
if("1".equals(str)){
throw new BusinessException("哈撒给");
}
return "sucess";
}
细说
统一异常处理主要依赖于@ControllerAdvice和@ExceptionHandler两个注解
@ControllerAdvice:作用于所有@Controller标注的Controller类
@ExceptionHandler:作用于所有@RequestMapping标注的方法抛出的指定类型的异常
更详细看这个大佬写的吧@ControllerAdvice 的介绍及三种用法