-
Notifications
You must be signed in to change notification settings - Fork 143
UNOMI-928: Improve REST API error handling with dedicated exception mappers #771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
b676a10
UNOMI-928: Improve REST API error handling with dedicated exception m…
sergehuber d8daa6e
Potential fix for pull request finding
sergehuber 534da10
Potential fix for pull request finding
sergehuber 77f2835
Potential fix for pull request finding
sergehuber fd7d7d9
Potential fix for pull request finding
sergehuber cf070f0
UNOMI-928: Fix queryParameters truncation and add missing tests
sergehuber File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
rest/src/main/java/org/apache/unomi/rest/exception/AbstractRestExceptionMapper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.apache.unomi.rest.exception; | ||
|
|
||
| import com.fasterxml.jackson.core.JsonParseException; | ||
| import com.fasterxml.jackson.databind.JsonMappingException; | ||
| import org.apache.cxf.jaxrs.utils.JAXRSUtils; | ||
| import org.apache.cxf.message.Message; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import javax.servlet.http.HttpServletRequest; | ||
| import javax.ws.rs.core.MediaType; | ||
| import javax.ws.rs.core.Response; | ||
| import javax.ws.rs.core.UriInfo; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * Base class for the REST {@code ExceptionMapper}s, factoring out the behaviour they share: | ||
| * building a sanitized request context for logging, walking to a root cause, detecting JSON | ||
| * deserialization failures, and producing the standard JSON error responses. | ||
| */ | ||
| public abstract class AbstractRestExceptionMapper { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRestExceptionMapper.class.getName()); | ||
|
|
||
| private static final String ERROR_MESSAGE_KEY = "errorMessage"; | ||
|
|
||
| /** | ||
| * @return a {@code 400 Bad Request} JSON response: {@code {"errorMessage":"badRequest"}} | ||
| */ | ||
| protected Response badRequestResponse() { | ||
| return jsonErrorResponse(Response.Status.BAD_REQUEST, "badRequest"); | ||
| } | ||
|
|
||
| /** | ||
| * @return a {@code 500 Internal Server Error} JSON response: {@code {"errorMessage":"internalServerError"}} | ||
| */ | ||
| protected Response internalServerErrorResponse() { | ||
| return jsonErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "internalServerError"); | ||
| } | ||
|
|
||
| private Response jsonErrorResponse(Response.Status status, String errorMessage) { | ||
| Map<String, Object> body = new HashMap<>(); | ||
| body.put(ERROR_MESSAGE_KEY, errorMessage); | ||
| return Response.status(status).header("Content-Type", MediaType.APPLICATION_JSON).entity(body).build(); | ||
| } | ||
|
|
||
| /** | ||
| * @return {@code true} when the given root cause is a Jackson deserialization failure, i.e. a | ||
| * client error (malformed/mistyped request body) rather than a genuine server fault. | ||
| */ | ||
| protected boolean isJsonDeserializationError(Throwable rootCause) { | ||
| return rootCause instanceof JsonMappingException || rootCause instanceof JsonParseException; | ||
| } | ||
|
|
||
| protected Throwable getRootCause(Throwable throwable) { | ||
| if (throwable == null) { | ||
| return null; | ||
| } | ||
| Throwable current = throwable; | ||
| java.util.Set<Throwable> visited = java.util.Collections.newSetFromMap(new java.util.IdentityHashMap<>()); | ||
| while (current.getCause() != null && current.getCause() != current && visited.add(current)) { | ||
| current = current.getCause(); | ||
| } | ||
| return current; | ||
| } | ||
|
Copilot marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * @return the throwable's message, or its simple class name when no message is available. | ||
| */ | ||
| protected String messageOrType(Throwable throwable) { | ||
| if (throwable == null) { | ||
| return ""; | ||
| } | ||
| String message = throwable.getMessage(); | ||
| return (message != null && !message.isEmpty()) ? message : throwable.getClass().getSimpleName(); | ||
| } | ||
|
|
||
| /** | ||
| * Builds a sanitized "METHOD /path?query" description of the current request for logging. | ||
| * Never throws: returns a placeholder when the request context cannot be resolved. | ||
| */ | ||
| protected String buildRequestContext() { | ||
| StringBuilder context = new StringBuilder(); | ||
| try { | ||
| Message message = JAXRSUtils.getCurrentMessage(); | ||
| if (message == null) { | ||
| return "REQUEST CONTEXT UNAVAILABLE"; | ||
| } | ||
| HttpServletRequest request = (HttpServletRequest) message.get("HTTP.REQUEST"); | ||
| if (request != null) { | ||
| appendFromServletRequest(context, request); | ||
| } else { | ||
| appendFromCxfMessage(context, message); | ||
| } | ||
| } catch (Exception e) { | ||
| LOGGER.debug("Error building request context", e); | ||
| return "REQUEST CONTEXT UNAVAILABLE"; | ||
| } | ||
| return context.toString(); | ||
| } | ||
|
|
||
| private void appendFromServletRequest(StringBuilder context, HttpServletRequest request) { | ||
| context.append(LogSanitizer.httpMethod(request.getMethod())) | ||
| .append(" ") | ||
| .append(LogSanitizer.url(request.getRequestURI())); | ||
| String queryString = request.getQueryString(); | ||
| if (queryString != null && !queryString.isEmpty()) { | ||
| context.append("?").append(LogSanitizer.queryString(queryString)); | ||
| } | ||
| } | ||
|
|
||
| private void appendFromCxfMessage(StringBuilder context, Message message) { | ||
| String httpMethod = (String) message.get(Message.HTTP_REQUEST_METHOD); | ||
| String basePath = (String) message.get(Message.BASE_PATH); | ||
| String pathInfo = (String) message.get(Message.PATH_INFO); | ||
| String requestURI = (String) message.get(Message.REQUEST_URI); | ||
|
|
||
| if (requestURI != null) { | ||
| context.append(sanitizedMethodOrUnknown(httpMethod)).append(" ").append(LogSanitizer.url(requestURI)); | ||
| } else if (basePath != null || pathInfo != null) { | ||
| String path = (basePath != null ? basePath : "") + (pathInfo != null ? pathInfo : ""); | ||
| context.append(sanitizedMethodOrUnknown(httpMethod)).append(" ").append(LogSanitizer.url(path)); | ||
| } else { | ||
| UriInfo uriInfo = message.get(UriInfo.class); | ||
| if (uriInfo != null) { | ||
| context.append("HTTP ").append(LogSanitizer.url(uriInfo.getPath())); | ||
| if (uriInfo.getQueryParameters() != null && !uriInfo.getQueryParameters().isEmpty()) { | ||
| context.append("?").append(LogSanitizer.queryParameters(uriInfo.getQueryParameters())); | ||
| } | ||
| } else { | ||
| context.append("UNKNOWN REQUEST"); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private String sanitizedMethodOrUnknown(String httpMethod) { | ||
| return httpMethod != null ? LogSanitizer.httpMethod(httpMethod) : "UNKNOWN"; | ||
| } | ||
| } | ||
81 changes: 81 additions & 0 deletions
81
rest/src/main/java/org/apache/unomi/rest/exception/InternalServerErrorExceptionMapper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.apache.unomi.rest.exception; | ||
|
|
||
| import org.osgi.service.component.annotations.Component; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import javax.ws.rs.InternalServerErrorException; | ||
| import javax.ws.rs.core.Response; | ||
| import javax.ws.rs.ext.ExceptionMapper; | ||
| import javax.ws.rs.ext.Provider; | ||
|
|
||
| /** | ||
| * Maps {@link InternalServerErrorException}. When the underlying cause is a Jackson deserialization | ||
| * failure (a wrapped client error) the response is downgraded to a {@code 400 Bad Request}; | ||
| * otherwise it remains a {@code 500 Internal Server Error} with detailed, sanitized logging. | ||
| */ | ||
| @Provider | ||
| @Component(service = ExceptionMapper.class) | ||
| public class InternalServerErrorExceptionMapper extends AbstractRestExceptionMapper | ||
| implements ExceptionMapper<InternalServerErrorException> { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(InternalServerErrorExceptionMapper.class.getName()); | ||
|
|
||
| @Override | ||
| public Response toResponse(InternalServerErrorException exception) { | ||
| String requestContext = buildRequestContext(); | ||
| Throwable rootCause = getRootCause(exception); | ||
|
|
||
| // A wrapped JSON deserialization failure is really a client error -> 400 Bad Request. | ||
| if (isJsonDeserializationError(rootCause)) { | ||
| String errorMessage = LogSanitizer.forLogging(messageOrType(rootCause)); | ||
| LOGGER.warn("Bad request on {} - JSON deserialization error: {} (Set InternalServerErrorExceptionMapper to debug to get the full stacktrace)", | ||
| requestContext, errorMessage); | ||
| LOGGER.debug("Full JSON mapping exception details for request: {}", requestContext, exception); | ||
| return badRequestResponse(); | ||
| } | ||
|
|
||
| // Genuine server error -> 500 with detailed context. | ||
| LOGGER.error("{} (Set InternalServerErrorExceptionMapper to debug to get the full stacktrace)", | ||
| buildServerErrorDetails(requestContext, exception, rootCause)); | ||
| LOGGER.debug("Full exception details for request: {}", requestContext, exception); | ||
|
Copilot marked this conversation as resolved.
|
||
|
|
||
| return internalServerErrorResponse(); | ||
| } | ||
|
|
||
| private String buildServerErrorDetails(String requestContext, InternalServerErrorException exception, Throwable rootCause) { | ||
| StringBuilder errorDetails = new StringBuilder(); | ||
| errorDetails.append("Request failed: ").append(requestContext); | ||
|
|
||
| if (rootCause != null && rootCause != exception) { | ||
| errorDetails.append(" - Root cause: ").append(LogSanitizer.className(rootCause.getClass().getSimpleName())); | ||
| String rootCauseMessage = rootCause.getMessage(); | ||
| if (rootCauseMessage != null && !rootCauseMessage.isEmpty()) { | ||
| errorDetails.append(" (").append(LogSanitizer.forLogging(rootCauseMessage)).append(")"); | ||
| } | ||
| } | ||
|
|
||
| String exceptionMessage = exception.getMessage(); | ||
| if (exceptionMessage != null && !exceptionMessage.isEmpty() | ||
| && (rootCause == null || !exceptionMessage.equals(rootCause.getMessage()))) { | ||
| errorDetails.append(" - Error: ").append(LogSanitizer.forLogging(exceptionMessage)); | ||
| } | ||
| return errorDetails.toString(); | ||
| } | ||
| } | ||
51 changes: 51 additions & 0 deletions
51
rest/src/main/java/org/apache/unomi/rest/exception/JsonMappingExceptionMapper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.apache.unomi.rest.exception; | ||
|
|
||
| import com.fasterxml.jackson.databind.JsonMappingException; | ||
| import org.osgi.service.component.annotations.Component; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| import javax.ws.rs.core.Response; | ||
| import javax.ws.rs.ext.ExceptionMapper; | ||
| import javax.ws.rs.ext.Provider; | ||
|
|
||
| /** | ||
| * Maps Jackson {@link JsonMappingException} (raised when a syntactically valid JSON body cannot be | ||
| * deserialized into the target type) to a {@code 400 Bad Request}, so a client mistake is not | ||
| * reported as a server error. | ||
| */ | ||
| @Provider | ||
| @Component(service = ExceptionMapper.class) | ||
| public class JsonMappingExceptionMapper extends AbstractRestExceptionMapper implements ExceptionMapper<JsonMappingException> { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(JsonMappingExceptionMapper.class.getName()); | ||
|
|
||
| @Override | ||
| public Response toResponse(JsonMappingException exception) { | ||
| String requestContext = buildRequestContext(); | ||
| String errorMessage = LogSanitizer.forLogging(messageOrType(exception)); | ||
|
|
||
| // Client error: log at WARN level, full stack trace only at debug level. | ||
| LOGGER.warn("Bad request on {} - JSON deserialization error: {} (Set JsonMappingExceptionMapper to debug to get the full stacktrace)", | ||
| requestContext, errorMessage); | ||
| LOGGER.debug("Full JSON mapping exception details for request: {}", requestContext, exception); | ||
|
|
||
| return badRequestResponse(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.