Spring Boot 捕捉全局異常 統(tǒng)一返回值的問題
在前后端分離的情況下,我們經(jīng)常會(huì)定義一個(gè)統(tǒng)一的反回?cái)?shù)據(jù)格式,通常都會(huì)包含狀態(tài)碼,返回信息,返回的數(shù)據(jù),是否成功等參數(shù)。
1、ResultCode
單獨(dú)定義了一個(gè)ReturnCode枚舉類用于存儲(chǔ)代碼和返回的Message
public enum ResultCode {
//成功
SUCCESS(200),
// 失敗
FAIL(400),
// 未認(rèn)證(簽名錯(cuò)誤)
UNAUTHORIZED(401),
// 接口不存在
NOT_FOUND(404),
// 服務(wù)器內(nèi)部錯(cuò)誤
INTERNAL_SERVER_ERROR(500);
public int code;
ResultCode(int code)
{
this.code=code;
}
}
2、ResponseResult
/*
統(tǒng)一返回信息
*/
public class ResponseResult<T> {
public int code; //返回狀態(tài)碼200成功
private String msg; //返回描述信息
private T data; //返回內(nèi)容體
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;
}
}
在定義一個(gè)統(tǒng)一返回類:
3、Response
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
新建測(cè)試用戶接口類
package com.example.demo.service;
import com.example.demo.entity.User;
public interface IUserService {
public User getUserInfo();
}
5、新建 UserServiceImpl
新建測(cè)試用戶信息服務(wù)類
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調(diào)用
@Autowired
UserService service;
@RequestMapping(value = "/getUserItem",method = RequestMethod.GET)
public ResponseResult<User> getUserItem(){
try {
User user = service.getUserInfo();
String[] arr= new String[]{"測(cè)試"};
return Response.makeOKRsp(user);
}catch (Exception e)
{
return Response.makeErrRsp("查詢用戶信息異常");
}
}
返回結(jié)果:

7、全局異常處理器
/**
* 全局異常處理
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/*============= 請(qǐng)求錯(cuò)誤 start ==============================================*/
/**
* HTTP 請(qǐng)求方式不支持異常
* HttpRequestMethodNotSupportedException
* @return {@link ResponseResult}
*/
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public ResponseResult httpRequestMethodNotSupportException(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
return Response.makeErrRsp("請(qǐng)求方式不支持異常");
}
/*============= 請(qǐng)求錯(cuò)誤 end ==============================================*/
}
修改一下getUserItem讓其拋出自定義查詢返回null的異常:

總結(jié)
到此這篇關(guān)于Spring Boot 捕捉全局異常 統(tǒng)一返回值的文章就介紹到這了,更多相關(guān)Spring Boot 捕捉全局異常 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java套接字(Socket)網(wǎng)絡(luò)編程入門
這篇文章主要介紹了Java套接字(Socket)網(wǎng)絡(luò)編程入門,Socket可以理解為是對(duì)TCP/IP協(xié)議的抽象,需要的朋友可以參考下2015-10-10
java后端請(qǐng)求兌現(xiàn)request的中文亂碼問題解決
文章主要講述了在處理處理方案工作中遇到中文亂碼問題的解決過程,通過復(fù)現(xiàn)和分析亂碼問題,發(fā)現(xiàn)是由于解碼規(guī)則和后端服務(wù)編碼不一致導(dǎo)致的,最終通過修改過濾器中的編碼設(shè)置解決了問題2025-02-02
idea創(chuàng)建Spring項(xiàng)目的方法步驟(圖文)
這篇文章主要介紹了idea創(chuàng)建Spring項(xiàng)目的方法步驟(圖文),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
Java實(shí)現(xiàn)的求解經(jīng)典羅馬數(shù)字和阿拉伯?dāng)?shù)字相互轉(zhuǎn)換問題示例
這篇文章主要介紹了Java實(shí)現(xiàn)的求解經(jīng)典羅馬數(shù)字和阿拉伯?dāng)?shù)字相互轉(zhuǎn)換問題,涉及java輸入輸出及字符串、數(shù)組的遍歷與轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
Spring Boot集成 Spring Boot Admin 監(jiān)控
這篇文章主要介紹了Spring Boot集成 Spring Boot Admin 監(jiān)控,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
logback TimeBasedRollingPolicy按天生成日志源碼解析
這篇文章主要為大家介紹了logback TimeBasedRollingPolicy按天生成日志源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11

