本篇内容介绍了“SpringBoot全局异常处理的作用和用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

十载的清镇网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。营销型网站的优势是能够根据用户设备显示端的尺寸不同,自动调整清镇建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。创新互联建站从事“清镇网站设计”,“清镇网站推广”以来,每个客户项目都认真落实执行。
1、为什么要全局异常处理
在实际开发中,如果不处理统一处理异常,那么前端在调用后端提供的接口,就会处理各种的异常结构,对于前端来说那可谓是一场灾难,这对前后端的协作也不友好。比如后端路径:/api/v1/index/user?id=222,如果前端未传入ID,那么SpringBoot就会报如下异常:
{"timestamp":"2021-03-30T15:22:46.139+00:00","status":400,"error":"Bad Request","message":"","path":"/api/v1/index/user"}或者是我们代码里面自定义异常throw new RuntimeException("用户信息未找到!");,对于Spring Boot来说抛出如下异常:
{"timestamp":"2021-03-30T15:25:55.657+00:00","status":500,"error":"Internal Server Error","message":"","path":"/api/v1/index/users"}而后端真的异常信息是用户信息未找到!,前端获取到500异常,完全不知后端的具体异常。基于这些就有必要全局统一处理异常。
2、实现全局异常处理
2.1 封装统一结构消息
在实现全局异常处理之前,我们先封装一个统一结构的消息对象。
消息类
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class RestResponse {
private String code;
private String message;
private Object data;
}异常状态枚举
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ExceptionStatusEnums {
OK("0","success"),
ERROR("1","error");
private String code;
private String msg;
}处理消息的工厂类
import com.tenghu.lf.enums.ExceptionStatusEnums;
import com.tenghu.lf.resp.RestResponse;
public class ResponseFactory {
private ResponseFactory(){
}
public static RestResponse getOkResponse(){
return new RestResponse(ExceptionStatusEnums.OK.getCode(),ExceptionStatusEnums.OK.getMsg(),null);
}
public static RestResponse getOkResponse(String message){
return new RestResponse(ExceptionStatusEnums.OK.getCode(),message,null);
}
public static RestResponse getOkResponse(Object data){
return new RestResponse(ExceptionStatusEnums.OK.getCode(),ExceptionStatusEnums.OK.getMsg(),data);
}
public static RestResponse getOkResponse(String message,Object data){
return new RestResponse(ExceptionStatusEnums.OK.getCode(),message,data);
}
public static RestResponse getErrorMessage(){
return new RestResponse(ExceptionStatusEnums.ERROR.getCode(),ExceptionStatusEnums.ERROR.getMsg(),null);
}
public static RestResponse getErrorMessage(String message){
return new RestResponse(ExceptionStatusEnums.ERROR.getCode(),message,null);
}
public static RestResponse getErrorMessage(String message,Object data){
return new RestResponse(ExceptionStatusEnums.ERROR.getCode(),message,data);
}
public static RestResponse getBuildMessage(String code,String message){
return new RestResponse(code,message,null);
}
public static RestResponse getBuildMessage(String code,String message,Object data){
return new RestResponse(code,message,data);
}
}2.2 实现全局异常
定义一个全局异常处理类,在类上加上@RestControllerAdvice注解,也可以使用@ControllerAdvice注解,只不过使用后者,需要在各个方法上加上@ResponseBody注解
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理自定义异常
* @param componentException
* @return
*/
@ExceptionHandler(ComponentException.class)
public RestResponse componentException(ComponentException componentException) {
componentException.printStackTrace();
return ResponseFactory.getBuildMessage(componentException.getCode(),componentException.getLocalizedMessage());
}
/**
* 处理请求参数异常
* @param e
* @return
*/
@ExceptionHandler(MissingServletRequestParameterException.class)
public RestResponse paramMissingException(MissingServletRequestParameterException e){
e.printStackTrace();
return ResponseFactory.getBuildMessage(HttpStatus.INTERNAL_SERVER_ERROR.value()+"",String.format("请求参数:%s不能为空!",e.getParameterName()));
}
/**
* 处理请求体异常
* @param e
* @return
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public RestResponse readableException(HttpMessageNotReadableException e){
e.printStackTrace();
return ResponseFactory.getBuildMessage(HttpStatus.INTERNAL_SERVER_ERROR.value()+"",String.format("请求参数体不能为空!%s",e.getLocalizedMessage()));
}
/**
* 处理其他未知的运行时异常
* @param runtimeException
* @return
*/
@ExceptionHandler(RuntimeException.class)
public RestResponse runtimeException(RuntimeException runtimeException) {
runtimeException.printStackTrace();
return ResponseFactory.getBuildMessage(HttpStatus.INTERNAL_SERVER_ERROR.value()+"",runtimeException.getLocalizedMessage());
}
/**
* 处理其他异常
* @param exception
* @return
*/
@ExceptionHandler(Exception.class)
public RestResponse otherException(Exception exception){
exception.printStackTrace();
return ResponseFactory.getErrorMessage(exception.getLocalizedMessage());
}
}3、测试
访问路径
/api/v1/index/user?name=小A,不传name的情况下。
{
"code": "500",
"message": "请求参数:name不能为空!",
"data": null
}访问路径
/api/v1/index/user?name=小A,传name的情况下。
{
"code": "0",
"message": "success",
"data": {
"id": "1111",
"name": "小A"
}
}访问路径
/api/v1/index,不传请求体。
{
"code": "500",
"message": "请求参数体不能为空!Required request body is missing: public com.tenghu.lf.resp.RestResponse com.tenghu.lf.controller.IndexController.save(com.tenghu.lf.entity.User)",
"data": null
}访问路径
/api/v1/index,传请求体。
{
"code": "0",
"message": "success",
"data": null
}“SpringBoot全局异常处理的作用和用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!
分享题目:SpringBoot全局异常处理的作用和用法
链接URL:http://www.jxjierui.cn/article/ijhsjs.html


咨询
建站咨询
