Spring Boot中如何实现全局异常捕获并统一返回特定格式的响应?

2026-05-24 06:461阅读0评论SEO问题
  • 内容介绍
  • 相关推荐

本文共计863个文字,预计阅读时间需要4分钟。

Spring Boot中如何实现全局异常捕获并统一返回特定格式的响应?

在前后端分离的情况下,我们通常会定义一个统一的返回数据格式,通常包含状态码、返回信息、返回数据以及是否成功等参数。例如:1、ResultCode、ReturnCode等参数分别定义了不同的用途,用于存储和表示返回结果。

在前后端分离的情况下,我们经常会定义一个统一的反回数据格式,通常都会包含状态码,返回信息,返回的数据,是否成功等参数。

1、ResultCode

单独定义了一个ReturnCode枚举类用于存储代码和返回的Message

public enum ResultCode { //成功 SUCCESS(200), // 失败 FAIL(400), // 未认证(签名错误) UNAUTHORIZED(401), // 接口不存在 NOT_FOUND(404), // 服务器内部错误 INTERNAL_SERVER_ERROR(500); public int code; ResultCode(int code) { this.code=code; } }

2、ResponseResult

/* 统一返回信息 */ public class ResponseResult<T> { public int code; //返回状态码200成功 private String msg; //返回描述信息 private T data; //返回内容体 public ResponseResult<T> setCode(ResultCode retCode) { this.code = retCode.code; return this; } public int getCode() { return code; } public ResponseResult<T> setCode(int code) { this.code = code; return this; } public String getMsg() { return msg; } public ResponseResult<T> setMsg(String msg) { this.msg = msg; return this; } public T getData() { return data; } public ResponseResult<T> setData(T data) { this.data = data; return this; } }

在定义一个统一返回类:

3、Response

Spring Boot中如何实现全局异常捕获并统一返回特定格式的响应?

public class Response { private final static String SUCCESS = "success"; private final static String FAIL = "fail"; public static <T> ResponseResult<T> makeOKRsp() { return new ResponseResult<T>().setCode(ResultCode.SUCCESS).setMsg(SUCCESS); } public static <T> ResponseResult<T> makeOKRsp(String message) { return new ResponseResult<T>().setCode(ResultCode.SUCCESS).setMsg(message); } public static <T> ResponseResult<T> makeOKRsp(T data) { return new ResponseResult<T>().setCode(ResultCode.SUCCESS).setMsg(SUCCESS).setData(data); } public static <T> ResponseResult<T> makeErrRsp(String message) { return new ResponseResult<T>().setCode(ResultCode.INTERNAL_SERVER_ERROR).setMsg(message); } public static <T> ResponseResult<T> makeRsp(int code, String msg) { return new ResponseResult<T>().setCode(code).setMsg(msg); } public static <T> ResponseResult<T> makeRsp(int code, String msg, T data) { return new ResponseResult<T>().setCode(code).setMsg(msg).setData(data); } }

4、新建IUserService

新建测试用户接口类

package com.example.demo.service; import com.example.demo.entity.User; public interface IUserService { public User getUserInfo(); }

5、新建UserServiceImpl

新建测试用户信息服务类

package com.example.demo.service.impl; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.stereotype.Service; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.SimpleFormatter; @Service public class UserServiceImpl implements IUserService { public User getUserInfo(){ User user = new User(); user.setName("jack"); user.setPassword(12341234); return user; } }

6、在controller调用

@Autowired UserService service; @RequestMapping(value = "/getUserItem",method = RequestMethod.GET) public ResponseResult<User> getUserItem(){ try { User user = service.getUserInfo(); String[] arr= new String[]{"测试"}; return Response.makeOKRsp(user); }catch (Exception e) { return Response.makeErrRsp("查询用户信息异常"); } }

返回结果:

7、全局异常处理器

/** * 全局异常处理 */ @RestControllerAdvice public class GlobalExceptionHandler { /*============= 请求错误 start ==============================================*/ /** * HTTP 请求方式不支持异常 * HttpRequestMethodNotSupportedException * @return {@link ResponseResult} */ @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) public ResponseResult httpRequestMethodNotSupportException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) { return Response.makeErrRsp("请求方式不支持异常"); } /*============= 请求错误 end ==============================================*/ }

修改一下getUserItem让其抛出自定义查询返回null的异常:

总结

到此这篇关于Spring Boot 捕捉全局异常 统一返回值的文章就介绍到这了,更多相关Spring Boot 捕捉全局异常 内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

本文共计863个文字,预计阅读时间需要4分钟。

Spring Boot中如何实现全局异常捕获并统一返回特定格式的响应?

在前后端分离的情况下,我们通常会定义一个统一的返回数据格式,通常包含状态码、返回信息、返回数据以及是否成功等参数。例如:1、ResultCode、ReturnCode等参数分别定义了不同的用途,用于存储和表示返回结果。

在前后端分离的情况下,我们经常会定义一个统一的反回数据格式,通常都会包含状态码,返回信息,返回的数据,是否成功等参数。

1、ResultCode

单独定义了一个ReturnCode枚举类用于存储代码和返回的Message

public enum ResultCode { //成功 SUCCESS(200), // 失败 FAIL(400), // 未认证(签名错误) UNAUTHORIZED(401), // 接口不存在 NOT_FOUND(404), // 服务器内部错误 INTERNAL_SERVER_ERROR(500); public int code; ResultCode(int code) { this.code=code; } }

2、ResponseResult

/* 统一返回信息 */ public class ResponseResult<T> { public int code; //返回状态码200成功 private String msg; //返回描述信息 private T data; //返回内容体 public ResponseResult<T> setCode(ResultCode retCode) { this.code = retCode.code; return this; } public int getCode() { return code; } public ResponseResult<T> setCode(int code) { this.code = code; return this; } public String getMsg() { return msg; } public ResponseResult<T> setMsg(String msg) { this.msg = msg; return this; } public T getData() { return data; } public ResponseResult<T> setData(T data) { this.data = data; return this; } }

在定义一个统一返回类:

3、Response

Spring Boot中如何实现全局异常捕获并统一返回特定格式的响应?

public class Response { private final static String SUCCESS = "success"; private final static String FAIL = "fail"; public static <T> ResponseResult<T> makeOKRsp() { return new ResponseResult<T>().setCode(ResultCode.SUCCESS).setMsg(SUCCESS); } public static <T> ResponseResult<T> makeOKRsp(String message) { return new ResponseResult<T>().setCode(ResultCode.SUCCESS).setMsg(message); } public static <T> ResponseResult<T> makeOKRsp(T data) { return new ResponseResult<T>().setCode(ResultCode.SUCCESS).setMsg(SUCCESS).setData(data); } public static <T> ResponseResult<T> makeErrRsp(String message) { return new ResponseResult<T>().setCode(ResultCode.INTERNAL_SERVER_ERROR).setMsg(message); } public static <T> ResponseResult<T> makeRsp(int code, String msg) { return new ResponseResult<T>().setCode(code).setMsg(msg); } public static <T> ResponseResult<T> makeRsp(int code, String msg, T data) { return new ResponseResult<T>().setCode(code).setMsg(msg).setData(data); } }

4、新建IUserService

新建测试用户接口类

package com.example.demo.service; import com.example.demo.entity.User; public interface IUserService { public User getUserInfo(); }

5、新建UserServiceImpl

新建测试用户信息服务类

package com.example.demo.service.impl; import com.example.demo.entity.User; import com.example.demo.service.UserService; import org.springframework.stereotype.Service; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.SimpleFormatter; @Service public class UserServiceImpl implements IUserService { public User getUserInfo(){ User user = new User(); user.setName("jack"); user.setPassword(12341234); return user; } }

6、在controller调用

@Autowired UserService service; @RequestMapping(value = "/getUserItem",method = RequestMethod.GET) public ResponseResult<User> getUserItem(){ try { User user = service.getUserInfo(); String[] arr= new String[]{"测试"}; return Response.makeOKRsp(user); }catch (Exception e) { return Response.makeErrRsp("查询用户信息异常"); } }

返回结果:

7、全局异常处理器

/** * 全局异常处理 */ @RestControllerAdvice public class GlobalExceptionHandler { /*============= 请求错误 start ==============================================*/ /** * HTTP 请求方式不支持异常 * HttpRequestMethodNotSupportedException * @return {@link ResponseResult} */ @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) public ResponseResult httpRequestMethodNotSupportException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) { return Response.makeErrRsp("请求方式不支持异常"); } /*============= 请求错误 end ==============================================*/ }

修改一下getUserItem让其抛出自定义查询返回null的异常:

总结

到此这篇关于Spring Boot 捕捉全局异常 统一返回值的文章就介绍到这了,更多相关Spring Boot 捕捉全局异常 内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!