programing

Spring REST API에서 HTTP 코드 200을 반환한다.

golfzon 2023. 2. 28. 23:57
반응형

Spring REST API에서 HTTP 코드 200을 반환한다.

다음 코드를 사용하여 값을 가진 http 링크를 수신합니다.

@PostMapping(value = "/v1/notification")
public String handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return "result successful result";
}

http 코드를 반환하는 방법200- 응답 성공 여부

그리고 예를 들어 코드 처리에 코드 예외가 있는 경우 오류를 반환하려면 어떻게 해야 합니까?404?

스프링을 사용하는 경우:

@PostMapping(value = "/v1/notification")
public ResponseEntity handleNotifications(@RequestParam("notification") String itemid) {
    // parse here the values
    return ResponseEntity.ok().build(); 
    //OR ResponseEntity.ok("body goes here");
}

사용하시는 경우@RestController기본적으로는 200이 반환됩니다.

그러나 어쨌든 특정 응답 상태를 설정할 수 있습니다.@ResponseStatus주석(메서드가 반환되는 경우에도)void또는 다음 방법으로 커스텀 응답을 반환할 수 있습니다.ResponseEntity.

EDIT: 오류 처리 추가

오류 처리를 위해 특정 응답 엔티티를 반환할 수 있습니다.

 return ResponseEntity.status(HttpStatus.FORBIDDEN)
            .body("some body ");

또는 를 사용할 수 있습니다.@ExceptionHandler:

   @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void handleError(Exception ex) {
        // TODO: log exception
    }

를 사용하여 메서드에 주석을 달아 수행할 수 있습니다(다만,200디폴트)는 다음과 같습니다.

일부 컨트롤러

@PostMapping(value = "/v1/notification")
@ResponseStatus(HttpStatus.OK)
public String handleNotifications(@RequestParam("notification") String itemid) throws MyException {
    if(someCondition) {
       throw new MyException("some message");
    }
    // parse here the values
    return "result successful result";
}

여기서 특정 예외를 처리할 때 커스텀코드를 반환하려면 이 처리를 위해 (단, 같은 컨트롤러에서 실행할 수 있습니다)를 개별적으로 작성합니다.이 컨트롤러에는 다음과 같이 특정 예외를 처리하는 방법이 필요합니다.

예외 처리 컨트롤러

@RestControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MyException.class)
    protected ResponseEntity<Object> handleMyException(MyException ex, WebRequest req) {
        Object resBody = "some message";
        return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
    }

}

다음과 같은 작업을 수행할 수 있습니다.

@PostMapping(value = "/v1/notification")
public ResponseEntity<String> handleNotifications(
 @RequestParam("notification") String itemid) {
   // parse here the values
   return new ResponseEntity<>("result successful result", 
   HttpStatus.OK);
}

언급URL : https://stackoverflow.com/questions/51735084/return-http-code-200-from-spring-rest-api

반응형