Spring MVC / HTTP

@ExceptionHandler

Select an exception handler for known failures. Boot 4.0.10 companion project; source-reviewed, not executed.

Formal Syntax & Structure

java syntaxjava
@ExceptionHandler(InventoryStore.Conflict.class)

Working Example

Example Snippetjava
package example.inventory;import org.springframework.http.*;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.*;import org.springframework.http.converter.HttpMessageNotReadableException;import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;@RestControllerAdvicepublic class InventoryErrors {    @ExceptionHandler(InventoryStore.Missing.class)    ProblemDetail missing() { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "Item not found"); }    @ExceptionHandler(InventoryStore.Conflict.class)    ProblemDetail conflict() { return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "SKU already exists"); }    @ExceptionHandler({MethodArgumentNotValidException.class, HttpMessageNotReadableException.class,        MethodArgumentTypeMismatchException.class, IllegalArgumentException.class})    ProblemDetail invalid() { return ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid request"); }}
Java Reference