Spring Boot 전역 이상 통일 반환 값 문제 포착

앞 뒤 가 분 리 된 상황 에서 우 리 는 항상 통 일 된 반 회 데이터 형식 을 정의 합 니 다.보통 상태 코드,정 보 를 되 돌려 주 고 돌아 오 는 데이터,성공 여부 등 매개 변 수 를 포함 합 니 다.
1、ResultCode
  코드 를 저장 하고 되 돌아 오 는 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

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 캡 처 전역 이상 내용 은 이전 글 을 검색 하거나 아래 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!

좋은 웹페이지 즐겨찾기