Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions openframe-exception/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,11 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ A `@RestControllerAdvice` base class that centralizes HTTP exception handling ac
| `handleResponseStatusException` | `ResponseStatusException` | Determined by exception |
| `handleException` | `Exception` (catch-all) | `500 Internal Server Error` |

**Logging:** a 4xx is the caller's mistake and is logged at WARN without a stack trace; a `BaseException` with a 5xx
status and the catch-all are logged at ERROR with the stack trace. `IllegalArgumentException` (400) keeps its stack
trace at WARN, because our own code throws it too.

**Private helpers:**
- `resolveFieldName` — resolves parameter name or falls back to positional index (`arg0`, `arg1`) when compiled without `-parameters`
- `buildValidationResponse` — constructs an `ErrorResponse` with field-level errors
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,17 @@ public class BaseGlobalExceptionHandler {

private static final Logger log = LoggerFactory.getLogger(BaseGlobalExceptionHandler.class);

/**
* A 4xx is the caller's mistake (unknown id, bad input, conflict): WARN without a stack trace, so it neither
* floods the logs nor looks like a server fault. A 5xx is ours: ERROR with the stack trace.
*/
@ExceptionHandler(BaseException.class)
public ResponseEntity<ErrorResponse> handleBaseException(BaseException ex) {
log.error("{}: {}", ex.getErrorCode().getCode(), ex.getMessage(), ex);
if (ex.getHttpStatus().is5xxServerError()) {
log.error("{}: {}", ex.getErrorCode().getCode(), ex.getMessage(), ex);
} else {
log.warn("{}: {}", ex.getErrorCode().getCode(), ex.getMessage());
}

ErrorResponse response = ErrorResponse.of(ex.getErrorCode(), ex.getMessage());

Expand Down Expand Up @@ -114,7 +122,7 @@ public ErrorResponse handleHandlerMethodValidation(HandlerMethodValidationExcept
@ExceptionHandler(MissingRequestHeaderException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleMissingRequestHeader(MissingRequestHeaderException ex) {
log.error("Missing required header: ", ex);
log.warn("Missing required header: {}", ex.getHeaderName());
return ErrorResponse.of(ErrorCode.BAD_REQUEST, "Required header '" + ex.getHeaderName() + "' is missing");
}

Expand All @@ -138,10 +146,14 @@ public ErrorResponse handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatch
String.format("Invalid value '%s' for parameter '%s'", ex.getValue(), ex.getName()));
}

/**
* Mapped to 400, but also thrown by our own code (a bad UUID or number read from stored data), so the stack
* trace is kept to tell the two apart.
*/
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleIllegalArgument(IllegalArgumentException ex) {
log.error("Invalid request: ", ex);
log.warn("Invalid request: {}", ex.getMessage(), ex);
return ErrorResponse.of(ErrorCode.BAD_REQUEST, ex.getMessage());
}

Expand All @@ -155,14 +167,14 @@ public ErrorResponse handleIllegalState(IllegalStateException ex) {
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public ErrorResponse handleMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
log.error("Method not supported: ", ex);
log.warn("Method not supported: {}", ex.getMessage());
return ErrorResponse.of(ErrorCode.METHOD_NOT_ALLOWED, ex.getMessage());
}

@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
public ErrorResponse handleMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex) {
log.error("Media type not supported: ", ex);
log.warn("Media type not supported: {}", ex.getMessage());
return ErrorResponse.of(ErrorCode.UNSUPPORTED_MEDIA_TYPE, ex.getMessage());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package com.openframe.core.exception;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import static org.assertj.core.api.Assertions.assertThat;

/** A 4xx is the caller's mistake: WARN without a stack trace. A 5xx is ours: ERROR with it. */
class BaseGlobalExceptionHandlerLoggingTest {

private final BaseGlobalExceptionHandler handler = new BaseGlobalExceptionHandler();
private final Logger logger = (Logger) LoggerFactory.getLogger(BaseGlobalExceptionHandler.class);
private final ListAppender<ILoggingEvent> appender = new ListAppender<>();

@BeforeEach
void attach() {
appender.start();
logger.addAppender(appender);
}

@AfterEach
void detach() {
logger.detachAppender(appender);
}

@Test
void notFoundIsAWarningWithoutAStackTrace() {
assertThat(handler.handleBaseException(new NotFoundException("Device x not found")).getStatusCode())
.isEqualTo(HttpStatus.NOT_FOUND);

assertOnlyEvent(Level.WARN, "NOT_FOUND: Device x not found", false);
}

@Test
void serverErrorIsAnErrorWithTheStackTrace() {
handler.handleBaseException(new ServerFault("Fleet unreachable"));

assertOnlyEvent(Level.ERROR, "INTERNAL_ERROR: Fleet unreachable", true);
}

@Test
void unsupportedMethodIsAWarningWithoutAStackTrace() {
handler.handleMethodNotSupported(new HttpRequestMethodNotSupportedException("DELETE"));

assertThat(appender.list).singleElement().satisfies(event -> {
assertThat(event.getLevel()).isEqualTo(Level.WARN);
assertThat(event.getThrowableProxy()).isNull();
});
}

@Test
void illegalArgumentIsAWarningThatKeepsItsStackTrace() {
handler.handleIllegalArgument(new IllegalArgumentException("Invalid UUID string: x"));

assertOnlyEvent(Level.WARN, "Invalid request: Invalid UUID string: x", true);
}

private void assertOnlyEvent(Level level, String message, boolean withStackTrace) {
assertThat(appender.list).singleElement().satisfies(event -> {
assertThat(event.getLevel()).isEqualTo(level);
assertThat(event.getFormattedMessage()).isEqualTo(message);
assertThat(event.getThrowableProxy() != null).isEqualTo(withStackTrace);
});
}

private static final class ServerFault extends BaseException {
ServerFault(String message) {
super(ErrorCode.INTERNAL_ERROR, HttpStatus.INTERNAL_SERVER_ERROR, message);
}
}
}
Loading