2016-09-20 3 views
0

응답 객체 r 오류에 따라 400, 400, 404 등의 HTTPStatus 코드를 동적으로 반환하고 싶습니다. Ive가이 질문을 인용 함 - Programmatically change http response status using spring 3 restful하지만 도움이되지 않습니다. @ExceptionHandler를 사용하여 요청에 따라 HTTP 상태 코드를 동적으로 반환하십시오.

필자 @ExceptionHandler 방법이 Controller 클래스

@ExceptionHandler(CustomException.class) 
    @ResponseBody 
    public ResponseEntity<?> handleException(CustomException e) { 
     return new ResponseEntity<MyErrorResponse>(
       new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())), 
       ExceptionUtility.getHttpCode(e.getCode())); 
    } 

ExceptionUtility 나는 위의 두 가지 방법 =의 getMessage 및 getCode이

public class ExceptionUtility { 
public static String getMessage(String message) { 
     return message; 
    } 

    public static HttpStatus getHttpCode(String code) { 
     return HttpStatus.NOT_FOUND; //how to return status code dynamically here ? 
    } 

내가 체크인하지 않으 사용했습니다 클래스입니다 조건에 따라 응답 코드를 반환하면 더 좋은 방법이 있습니까?

답변

0

서로 다른 예외에 대해 서로 다른 예외 핸들러를 정의하고 다음과 같이 @ResponseStatus를 사용해야합니다 :

@ResponseStatus(HttpStatus.UNAUTHORIZED) 
    @ExceptionHandler({ UnAuthorizedException.class }) 
    public @ResponseBody ExceptionResponse unAuthorizedRequestException(final Exception exception) { 

     return response; 
    } 

@ResponseStatus(HttpStatus.CONFLICT) 
    @ExceptionHandler({ DuplicateDataException.class }) 
    public @ResponseBody ExceptionResponse DuplicateDataRequestException(final Exception exception) { 

     return response; 
    } 

@ResponseStatus(HttpStatus.BAD_REQUEST) 
    @ExceptionHandler({ InvalidException.class }) 
    public @ResponseBody ExceptionResponse handleInvalidException(final Exception exception) { 

     return response; 
    } 
+0

이 더 좋은 방법이보다 없을까요? – user2340345

+0

이것은 Spring 예외 처리기가 작동하는 방법입니다. 당신이 봄을 사용한다면 이것과 함께 갈 수 있습니다. – Suraj