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 캡 처 전역 이상 내용 은 이전 글 을 검색 하거나 아래 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.