歡迎您光臨本站 註冊首頁

Spring Boot 捕捉全局異常 統一返回值的問題

←手機掃碼閱讀     wooen @ 2020-06-18 , reply:0

 在前後端分離的情況下,我們經常會定義一個統一的反回數據格式,通常都會包含狀態碼,返回信息,返回的數據,是否成功等參數。

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{   public int code; //返回狀態碼200成功      private String msg; //返回描述信息      private T data; //返回內容體      public ResponseResultsetCode(ResultCode retCode) {    this.code = retCode.code;    return this;   }      public int getCode() {    return code;   }      public ResponseResultsetCode(int code) {    this.code = code;    return this;   }      public String getMsg() {    return msg;   }      public ResponseResultsetMsg(String msg) {    this.msg = msg;    return this;   }      public T getData() {    return data;   }      public ResponseResultsetData(T data) {    this.data = data;    return this;   }     }

 

在定義一個統一返回類:

3、Response

  public class Response {   private final static String SUCCESS = "success";      private final static String FAIL = "fail";      public staticResponseResultmakeOKRsp() {    return new ResponseResult().setCode(ResultCode.SUCCESS).setMsg(SUCCESS);   }      public staticResponseResultmakeOKRsp(String message) {    return new ResponseResult().setCode(ResultCode.SUCCESS).setMsg(message);   }      public staticResponseResultmakeOKRsp(T data) {    return new ResponseResult().setCode(ResultCode.SUCCESS).setMsg(SUCCESS).setData(data);   }      public staticResponseResultmakeErrRsp(String message) {    return new ResponseResult().setCode(ResultCode.INTERNAL_SERVER_ERROR).setMsg(message);   }      public staticResponseResultmakeRsp(int code, String msg) {    return new ResponseResult().setCode(code).setMsg(msg);   }      public staticResponseResultmakeRsp(int code, String msg, T data) {    return new ResponseResult().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 ResponseResultgetUserItem(){    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的異常:

 


[wooen ] Spring Boot 捕捉全局異常 統一返回值的問題已經有264次圍觀

http://coctec.com/docs/java/show-post-238969.html