如何在SpringBoot项目里进行统一异常处理
需要了解的知识
@ControllerAdvice的作用
1、处理前
异常代码
@ApiOperation(value = "根据id获取医院设置")
@GetMapping("/findHospById/{id}")
public Result findHospById(@PathVariable Long id) {
int a = 1 / 0;
HospitalSet hospitalSet = hospitalSetService.getById(id);
return Result.ok(hospitalSet);
}
Swagger2输出结果
![image-20220202214712150](https://img-blog.csdnimg.cn/img_convert/9abda4aac00194ec0680d61455140594.png)
2、进行系统异常全局处理
添加全局异常处理类
![image-20220202215154305](https://img-blog.csdnimg.cn/img_convert/a9230c1c1f394fd0c2f030454e32e117.png)
代码
package com.fafa.yygh.common.exception;
import com.fafa.yygh.common.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e) {
e.printStackTrace();
return Result.fail();
}
}
Swagger2结果
![image-20220202215407159](https://img-blog.csdnimg.cn/img_convert/a8808a8142da506d69ef8ac893279caf.png)
3、进行自定义异常处理
开发时,往往需要我们去定义处理一些异常(这里还是那上面的那个异常来做测试)
创建自定义异常处理类
package com.fafa.yygh.common.exception;
import com.fafa.yygh.common.result.ResultCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(value = "自定义全局异常类")
public class YyghException extends RuntimeException {
@ApiModelProperty(value = "异常状态码")
private Integer code;
public YyghException(String message, Integer code) {
super(message);
this.code = code;
}
public YyghException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
}
@Override
public String toString() {
return "YyghException{" +
"code=" + code +
", message=" + this.getMessage() +
'}';
}
}
将其添加到GlobalExceptionHandler
@ExceptionHandler(YyghException.class)
@ResponseBody
public Result divError(YyghException e) {
return Result.build(e.getCode(), e.getMessage());
}
![image-20220202215737501](https://img-blog.csdnimg.cn/img_convert/67109438889c7126dc475e87e980f964.png)
需要手动 try catch 一下
![image-20220202215919100](https://img-blog.csdnimg.cn/img_convert/dd8c71232429891134cb6ee0f59729f0.png)
效果
swagger和系统异常处理一样
不过后台输出不一样
![image-20220202220034953](https://img-blog.csdnimg.cn/img_convert/4664047bb8b893f76581fdff66a2a9cb.png)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)