Spring exceptions

Report a typo

Spring throws MissingPathVariableException if the path variable name in URI does not match the path variable name declared in the method parameter. For example:

Java
@GetMapping("/test/{number}")
public String test(@PathVariable int id) {
    return "success";
}
Kotlin
@GetMapping("/test/{number}")
fun test(@PathVariable id: Int): String {
    return "success"
}

Here, the path variable name in the URI (number) does not match the method parameter name (id), that's why Spring will throw a MissingPathVariableException.

Let's create a handler for customizing this type of exception using the ResponseEntityExceptionHandler class! Complete the following snippet:

Java
{1}
public class ControllerExceptionHandler extends {2} {

    {3}
    protected ResponseEntity<Object> {4}(
            {5} ex,
            HttpHeaders headers,
            HttpStatusCode status,
            WebRequest request) {

        Map<String, Object> body = new HashMap<>();
        body.put("status", status.value());
        body.put("exception", ex.getMessage());
        body.put("description", request.getDescription(false));

        return new ResponseEntity<>(body, headers, status);
    }
}
Kotlin
{1}
class ControllerExceptionHandler : {2} {

    {3}
    fun {4} (
        ex: {5},
        headers: HttpHeaders,
        status: HttpStatusCode,
        request: WebRequest
    ): ResponseEntity<Any>  {

        val body =  HashMap<String, Any>()
        body["status"] = status.value()
        body["exception"] = ex.getMessage()
        body["description"] = request.getDescription(false)

        return ResponseEntity(body, headers, status)
    }
}
Match the items from left and right columns
{1}
{2}
{3}
{4}
{5}
handleMissingPathVariable
@ControllerAdvice
@Override
MissingPathVariableException
ResponseEntityExceptionHandler
___

Create a free account to access the full topic