programing

스프링 부트에서 다양한 유형의 ResponseEntity를 반환하는 가장 좋은 방법(스프링에서의 REST 오류 처리)

javajsp 2023. 3. 5. 09:29

스프링 부트에서 다양한 유형의 ResponseEntity를 반환하는 가장 좋은 방법(스프링에서의 REST 오류 처리)

REST 을 단단 rest REST에 .Spring Boot )Spring★★★★★★★★★★★★★★★★★★」

ResponseEntity<Success>컨트롤러 레벨에서의 성공 응답으로서 사용됩니다.그러나 완전히 다른 오류 응답을 반환하고 싶다.ResponseEntity<Error>에러(검증 에러, 로직 에러, 런타임 에러)가 있는 경우.

성공오류 응답은 응용 프로그램에 따라 완전히 다릅니다. Success&Error는 어플리케이션이 성공 및 오류 응답을 나타내기 위해 사용하는2개의 Java 클래스입니다.

의 ᄃ자를 돌려주는 가장 좋은 방법은 요?ResponseEntitySpring-Boot:Spring

봄을 합니다.@ControllerAdvice에러를 처리합니다."스프링 부트 오류 처리" 섹션부터 시작하여 이 가이드를 읽어 보십시오.자세한 논의를 위해 Spring.io 블로그에 2018년 4월에 업데이트된 기사가 있습니다.

이 기능의 간단한 개요:

  • 는 반환만 .ResponseEntity<Success>에러 또는 예외 응답을 반환할 책임은 없습니다.
  • 모든 컨트롤러의 예외를 처리하는 클래스를 구현합니다.에는 '하다'가 .@ControllerAdvice
  • 에는, 「어드바이저」라고 코멘트가 붙은 메서드가 되어 있습니다.@ExceptionHandler
  • 각 예외 핸들러 메서드는 하나 이상의 예외 유형을 처리하도록 구성됩니다.이러한 방법에서는 오류에 대한 응답 유형을 지정할 수 있습니다.
  • 예를 들어 (컨트롤러 어드바이스 클래스에서) 검증 오류 예외 핸들러 메서드를 선언합니다.은 '돌아가다' 입니다.ResponseEntity<Error>

이 방법에서는 API 내의 모든 엔드포인트에 대해 컨트롤러 예외 처리를 한 곳에 구현하기만 하면 됩니다.또한 API가 모든 엔드포인트에서 동일한 예외 응답 구조를 쉽게 가질 수 있습니다.이것에 의해, 클라이언트의 예외 처리가 간소화됩니다.

와일드카드 「」를 할 수 .<?>Success ★★★★★★★★★★★★★★★★★」Error 매핑

public ResponseEntity<?> method() {
    boolean b = // some logic
    if (b)
        return new ResponseEntity<Success>(HttpStatus.OK);
    else
        return new ResponseEntity<Error>(HttpStatus.CONFLICT); //appropriate error code
}

@Mark Norman의 답변은 올바른 접근법이다.

스프링 2에서는 이를 사용하여 String, 다른 HTTP 상태 코드, DTO를 동시반환할 수 있는 Response Status Exception이 도입되었습니다.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

잘은 모르겠지만, 제 생각엔@ResponseEntity ★★★★★★★★★★★★★★★★★」@ResponseBody 것을 것은 이고, , 성공 성공 등의 입니다.

@RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
Book bookInfo2() {
    Book book = new Book();
    book.setBookName("Ramcharitmanas");
    book.setWriter("TulasiDas");
    return book;
}

@RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE )
public ResponseEntity<Book> bookInfo3() {
    Book book = new Book();
    book.setBookName("Ramayan");
    book.setWriter("Valmiki");
    return ResponseEntity.accepted().body(book);
}

상세한 것에 대하여는, http://www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity 를 참조해 주세요.

다음과 같이 객체 또는 문자열과 함께 지도를 사용할 수 있습니다.

@RequestMapping(value = "/path", 
        method = RequestMethod.GET, 
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<Map<String,String>> getData(){

    Map<String,String> response = new HashMap<String, String>();

    boolean isValid = // some logic
    if (isValid){
        response.put("ok", "success saving data");
        return ResponseEntity.accepted().body(response);
    }
    else{
        response.put("error", "an error expected on processing file");
        return ResponseEntity.badRequest().body(response);
    }

}

방법은 다음과 같습니다.

public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint.

 try {
  Integer.parseInt(player);
  return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST);
 } catch (Exception e) {


 }
 Message msg = new Message(player, "Hello " + player);
 return new ResponseEntity < Message > (msg, HttpStatus.OK);

}

@RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint.

 try {
  Integer.parseInt(player);
  List < ErrorResponse > errs = new ArrayList < ErrorResponse > ();
  errs.add(new ErrorResponse("111", "player is not found"));
  return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST);
 } catch (Exception e) {


 }
 Message msg = new Message(player, "Hello " + player);
 List < Message > msgList = new ArrayList < Message > ();
 msgList.add(msg);
 return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK);

}

동일한 요청 매핑 메서드에서 성공과 오류를 반환하기 위해 다음과 같이 구현할 수도 있습니다. Object class(java에서는 모든 클래스의 부모 클래스):-

public ResponseEntity< Object> method() {                                                                                                                                                                                                                                                                                                                                                                                  
    boolean b = //  logic  here   
      if (b)  
        return new ResponseEntity< Object>(HttpStatus.OK);      
    else      
        return new ResponseEntity< Object>(HttpStatus.CONFLICT); //appropriate error code   
}

가능ResponseEntity하지 않고

public ResponseEntity method() {
    boolean isValid = // some logic
    if (isValid){
        return new ResponseEntity(new Success(), HttpStatus.OK);
    }
    else{
        return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST);
    }
}

커스텀 예외 클래스를 사용하면 다른 HTTP 상태 코드와 dto 개체를 반환할 수 있습니다.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new UserNotFoundException("A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

예외 클래스

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
}

나는 이런 수업을 이용하곤 했다.statusCode 는, 에러 메세지가 메세지로 설정되어 있는 경우에 설정됩니다.데이터는 맵 또는 목록에 적절한 형태로 저장됩니다.

/**
* 
*/
package com.test.presentation.response;

import java.util.Collection;
import java.util.Map;

/**
 * A simple POJO to send JSON response to ajax requests. This POJO enables  us to
 * send messages and error codes with the actual objects in the application.
 * 
 * 
 */
@SuppressWarnings("rawtypes")
public class GenericResponse {

/**
 * An array that contains the actual objects
 */
private Collection rows;

/**
 * An Map that contains the actual objects
 */
private Map mapData;

/**
 * A String containing error code. Set to 1 if there is an error
 */
private int statusCode = 0;

/**
 * A String containing error message.
 */
private String message;

/**
 * An array that contains the actual objects
 * 
 * @return the rows
 */
public Collection getRows() {
    return rows;
}

/**
 * An array that contains the actual objects
 * 
 * @param rows
 *            the rows to set
 */
public void setRows(Collection rows) {
    this.rows = rows;
}

/**
 * An Map that contains the actual objects
 * 
 * @return the mapData
 */
public Map getMapData() {
    return mapData;
}

/**
 * An Map that contains the actual objects
 * 
 * @param mapData
 *            the mapData to set
 */
public void setMapData(Map mapData) {
    this.mapData = mapData;
}

/**
 * A String containing error code.
 * 
 * @return the errorCode
 */
public int getStatusCode() {
    return statusCode;
}

/**
 * A String containing error code.
 * 
 * @param errorCode
 *            the errorCode to set
 */
public void setStatusCode(int errorCode) {
    this.statusCode = errorCode;
}

/**
 * A String containing error message.
 * 
 * @return the errorMessage
 */
public String getMessage() {
    return message;
}

/**
 * A String containing error message.
 * 
 * @param errorMessage
 *            the errorMessage to set
 */
public void setMessage(String errorMessage) {
    this.message = errorMessage;
}

}

이게 도움이 됐으면 좋겠다.

할 , 「」가 .ResponseStatusExceptionHttp 러 http http http 。

따라서 제네릭스를 의도한 대로 효과적으로 사용할 수 있습니다.

유일하게 조금 어려운 것은 상태 204(본문 없음 OK)의 응답 타입입니다.는 그 을 '아주 좋다'라고 이 있다.ResponseEntity<?>, 냐냐ResponseEntity<Void>예측성이 떨어집니다.

예외적인 경우에는 응용 프로그램에서 HTTP API에 대한 RFC-7807 Problem Details 표준을 채택할 것을 권장합니다.

Zalando의 「봄의 문제」는, Spring Boot 와의 뛰어난 통합을 실현.기존의 Spring Boot 베이스의 애플리케이션과 간단하게 통합할 수 있습니다.JHIPster가 했던 것처럼요

어플리케이션에서 RFC-7087을 채택한 후 컨트롤러 메서드에 예외를 적용하기만 하면 다음과 같은 상세하고 표준적인 오류 응답을 얻을 수 있습니다.

   {
    "type": "https://example.com/probs/validation-error",
    "title": "Request parameter is malformed.",
    "status": 400
    "detail": "Validation error, value of xxx should be a positive number.",
    "instance": "/account/12345/msgs/abc",
   }

@MarkNorman의 답변을 팔로업하려면 , 다음의 예외에 대해서, 매핑을 정의할 필요가 있습니다.serviceyour controller(HTTP ' ' ' ' ' ) 。

  • 은 " "에 .200
  • 에 " " " 가 있습니다.400
  • 수 . 레코드는 없습니다.404
  • 기타 500

예를 들어 코드는 다음과 같습니다.

@GetMapping("/persons/{id}")
public ResponseEntity<Success> findPersonById(@PathVariable("id") Long id) {
    try {
        var person = service.findById(id);
        var message = new Message(HttpStatus.OK, getCurrentDateTime(), person);
        return message;
    } catch(ServiceException exception) {
        throw new NotFoundException("An error occurs while finding a person", exception);
    }
}

.ControllerAdvice

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<Error> handleNotFoundException(NotFoundException exception) {
    var error = new Error(HttpStatus.NOT_FOUND,
                getCurrentDateTime(),
                exception.getMessage());

    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}

이해해야 할 가장 중요한 것은 이 모든 것이RestControllersHTTP를 사용합니다.

오류 발생 시 @ExceptionHandler Controller Advisory를 사용하여 커스텀 Return Object를 반환할 수 있습니다.아래 코드 예를 참조하십시오.검증 오류 시 에서 400을 반환하고 커스텀 응답을 반환합니다.

@ControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler(value = InputValidationError.class)
    public ResponseEntity<ValidationErrorResponse> handleException(InputValidationError ex){
        return ResponseEntity.badRequest().body(ex.validationErrorResponse);
    }
}

언급URL : https://stackoverflow.com/questions/38117717/what-is-the-best-way-to-return-different-types-of-responseentity-in-spring-boot