programing

사용자 지정 메시지를 사용한 Jackson 예외 포착 및 처리

javajsp 2023. 6. 23. 21:46

사용자 지정 메시지를 사용한 Jackson 예외 포착 및 처리

제가 개발 중인 스프링부트 API에서 발생하는 잭슨 예외를 파악하고 싶습니다.예를 들어, 저는 다음과 같은 요청 클래스를 가지고 있으며 JSON 요청 개체의 "설문지 응답" 키가 null이거나 공백일 때 발생하는 오류를 포착하고 싶습니다." "요청 개체에 있습니다.

@Validated
@JsonRootName("questionnaireResponse")
public class QuestionnaireResponse {

    @JsonProperty("identifier")
    @Valid
    private Identifier identifier = null;

    @JsonProperty("basedOn")
    @Valid
    private List<Identifier_WRAPPED> basedOn = null;

    @JsonProperty("parent")
    @Valid
    private List<Identifier_WRAPPED> parent = null;

    @JsonProperty("questionnaire")
    @NotNull(message = "40000")
    @Valid
    private Identifier_WRAPPED questionnaire = null;

    @JsonProperty("status")
    @NotNull(message = "40000")
    @NotEmptyString(message = "40005")
    private String status = null;

    @JsonProperty("subject")
    @Valid
    private Identifier_WRAPPED subject = null;

    @JsonProperty("context")
    @Valid
    private Identifier_WRAPPED context = null;

    @JsonProperty("authored")
    @NotNull(message = "40000")
    @NotEmptyString(message = "40005")
    @Pattern(regexp = "\\d{4}-(?:0[1-9]|[1-2]\\d|3[0-1])-(?:0[1-9]|1[0-2])T(?:[0-1]\\d|2[0-3]):[0-5]\\d:[0-5]\\dZ", message = "40001")
    private String authored;

    @JsonProperty("author")
    @NotNull(message = "40000")
    @Valid
    private QuestionnaireResponseAuthor author = null;

    @JsonProperty("source")
    @NotNull(message = "40000")
    @Valid
    private Identifier_WRAPPED source = null; //    Reference(Patient | Practitioner | RelatedPerson) resources not implemented

    @JsonProperty("item")
    @NotNull(message = "40000")
    @Valid
    private List<QuestionnaireResponseItem> item = null;

    public Identifier getIdentifier() {
        return identifier;
    }

    public void setIdentifier(Identifier identifier) {
        this.identifier = identifier;
    }

    public List<Identifier_WRAPPED> getBasedOn() {
        return basedOn;
    }

    public void setBasedOn(List<Identifier_WRAPPED> basedOn) {
        this.basedOn = basedOn;
    }

    public List<Identifier_WRAPPED> getParent() {
        return parent;
    }

    public void setParent(List<Identifier_WRAPPED> parent) {
        this.parent = parent;
    }

    public Identifier_WRAPPED getQuestionnaire() {
        return questionnaire;
    }

    public void setQuestionnaire(Identifier_WRAPPED questionnaire) {
        this.questionnaire = questionnaire;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Identifier_WRAPPED getSubject() {
        return subject;
    }

    public void setSubject(Identifier_WRAPPED subject) {
        this.subject = subject;
    }

    public Identifier_WRAPPED getContext() {
        return context;
    }

    public void setContext(Identifier_WRAPPED context) {
        this.context = context;
    }

    public String getAuthored() {
        return authored;
    }

    public void setAuthored(String authored) {
        this.authored = authored;
    }

    public QuestionnaireResponseAuthor getAuthor() {
        return author;
    }

    public void setAuthor(QuestionnaireResponseAuthor author) {
        this.author = author;
    }

    public Identifier_WRAPPED getSource() {
        return source;
    }

    public void setSource(Identifier_WRAPPED source) {
        this.source = source;
    }

    public List<QuestionnaireResponseItem> getItem() {
        return item;
    }

    public void setItem(List<QuestionnaireResponseItem> item) {
        this.item = item;
    }
}

다음과 같은 Jackson 오류가 발생합니다.

{
    "Map": {
        "timestamp": "2018-07-25T12:45:32.285Z",
        "status": 400,
        "error": "Bad Request",
        "message": "JSON parse error: Root name '' does not match expected ('questionnaireResponse') for type [simple type, class com.optum.genomix.model.gel.QuestionnaireResponse]; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Root name '' does not match expected ('questionnaireResponse') for type [simple type, class com.optum.genomix.model.gel.QuestionnaireResponse]\n at [Source: (PushbackInputStream); line: 2, column: 3]",
    "path": "/api/optumhealth/genomics/v1.0/questionnaireResponse/create"
    }
}

이러한 예외(JsonRootName이 null/invalid인 예)를 포착하고 처리할 수 있는 방법이 있습니까? ResponseEntity를 확장하는 @ControllerAdvise 클래스와 유사할 수 있습니다.예외 처리기?

다음과 같은 방법을 사용해 보십시오.

@ControllerAdvice
public class ExceptionConfiguration extends ResponseEntityExceptionHandler {

    @ExceptionHandler(JsonMappingException.class) // Or whatever exception type you want to handle
    public ResponseEntity<SomeErrorResponsePojo> handleConverterErrors(JsonMappingException exception) { // Or whatever exception type you want to handle
        return ResponseEntity.status(...).body(...your response pojo...).build();
    }

}

이를 통해 모든 유형의 예외를 처리하고 그에 따라 응답할 수 있습니다.응답 상태가 항상 동일한 경우에는 다음과 같이 하십시오.@ResponseStatus(HttpStatus.some_status)방법과 요구에 따라ResponseEntity.body(...)

유사한 문제와 함께 이 질문을 찾았지만 내 질문만 다른 JSON 구문 분석 오류였습니다.

JSON parse error: Unrecognized character escape 'w' (code 119); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unrecognized character escape 'w' (code 119)\n at [Source: (PushbackInputStream); line: 1, column: 10] 

REST JSON 요청에서 그렇게 왔습니다.

{"query":"\\w"}

Rest Controller를 수정할 수 있는 경우 다음과 같이 JSON 구문 분석 오류를 발견할 수 있습니다.HttpMessageNotReadableException(Spring Boot에서 사용한 작업)@RestController주석).비록 나는 그 오류를 잡을 수 없었지만,@ExceptionHandler(Exception.class)

직렬화된 개체(자연스럽게 JSON으로 변환됨)를 사용하여 사용자 정의 JSON으로 응답할 수 있습니다.또한 처음부터 문제를 일으킨 요청 및 예외를 지정할 수 있습니다.따라서 세부 정보를 얻거나 오류 메시지를 수정할 수 있습니다.

@ResponseBody
@ExceptionHandler(HttpMessageNotReadableException.class)
private SerializableResponseObject badJsonRequestHandler(HttpServletRequest req, Exception ex) {

    SerializableResponseObject response = new SerializableResponseObject(404,
                "Bad Request",
                "Invalid request parameters, could not create query",
                req.getRequestURL().toString())

    Logger logger = LoggerFactory.getLogger(UserController.class);
    logger.error("Exception: {}\t{}\t", response);

    return response;
}

코드는 다음과 같은 것을 반환합니다.

{
  "timestamp": "Thu Oct 17 10:19:48 PDT 2019",
  "status": 404,
  "error": "Bad Request",
  "message": "Invalid request parameters, could not create query",
  "path": "http://localhost:8080/user/query"
}

그리고 다음과 같은 것을 기록할 것입니다.

Exception: [Thu Oct 17 10:19:48 PDT 2019][404][http://localhost:8080/user/query][Bad Request]: Invalid request parameters, could not create query

직렬화 가능한 응답 개체의 코드

public class SerializableResponseObject implements Serializable {
    public String timestamp;
    public Integer status;
    public String error;
    public String message;
    public String path;

    public SerializableResponseObject(Integer status, String error, String message, String path) {
        this.timestamp = (new Date()).toString();
        this.status = status;
        this.error = error;
        this.message = message;
        this.path = path;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public Integer getStatus() {
        return status;
    }

    public String getError() {
        return error;
    }

    public String getMessage() {
        return message;
    }

    public String getPath() {
        return path;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public void setError(String error) {
        this.error = error;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String toString() {
        return "[" + this.timestamp + "][" + this.status + "][" + this.path + "][" + this.error + "]: " + this.message;
    }
}

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

@ExceptionHandler(HttpMessageNotReadableException.class)
public CustomResponse handleJsonException(HttpServletResponse response, HttpMessageNotReadableException ex) {
        return customGenericResponse(ex);
    }

public CustomResponse customGenericResponse(HttpMessageNotReadableException ex) {
    //here build your custom response
    CustomResponse customResponse = new CustomResponse();
    GenericError error = new GenericError();
    error.setMessage(ex.getMessage()); 
    error.setCode(500);
    customResponse.setError(error);
    return customResponse;
}

사용자 지정 응답:

public class CustomResponse {
    Object data;
    GenericError error;
}

public class GenericError {
    private Integer code;
    private String message;
}

customGenericResponse(customGenericResponse) 내에서 ex(ex)의 원인 인스턴스를 확인하고 그에 따라 사용자 정의 오류 메시지를 반환할 수 있습니다.

예, 할 수 있습니다. 핸들러를 구현합니다.인터셉터.이를 통해 사용자 지정 메시지를 주고자 하는 경우 요청 & &을 사전 처리한 @ControllerAdvise로 예외를 처리할 수 있습니다.

public class CustomInterceptor implements HandlerInterceptor{

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    //your custom logic here.
    return true;
}
}

이 인터셉터를 구성해야 합니다.

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry){
    registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/**");
}
}

핸들 예외는 다음과 같습니다.

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler {

private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(JsonProcessingException.class)
public void handleJsonException(HttpServletResponse response, Exception ex) {
   //here build your custom response
    prepareErrorResponse(response,UNPROCESSABLE_ENTITY,"");
}


private void prepareErrorResponse(HttpServletResponse response, HttpStatus status, String apiError) {
    response.setStatus(status.value());
    try(PrintWriter writer = response.getWriter()) {
        new ObjectMapper().writeValue(writer, apiError);
    } catch (IOException ex) {
        logger.error("Error writing string to response body", ex);
    }
}
}

언급URL : https://stackoverflow.com/questions/51519381/catching-handling-jackson-exceptions-with-a-custom-message