@@ -1440,6 +1440,37 @@ is to handle `text/html` specifically and provide a fallback for everything else
1440
1440
just extend `BasicErrorController` and add a public method with a `@RequestMapping` that
1441
1441
has a `produces` attribute, and create a bean of your new type.
1442
1442
1443
+ You can also define a `@ControllerAdvice` to customize the JSON document to return for a
1444
+ particular controller and/or exception type.
1445
+
1446
+ [source,java,indent=0,subs="verbatim,quotes,attributes"]
1447
+ ----
1448
+
1449
+ @ControllerAdvice(basePackageClasses = FooController.class)
1450
+ public class FooControllerAdvice extends ResponseEntityExceptionHandler {
1451
+
1452
+ @ExceptionHandler(YourException.class)
1453
+ @ResponseBody
1454
+ ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
1455
+ HttpStatus status = getStatus(request);
1456
+ return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
1457
+ }
1458
+
1459
+ private HttpStatus getStatus(HttpServletRequest request) {
1460
+ Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
1461
+ if (statusCode == null) {
1462
+ return HttpStatus.INTERNAL_SERVER_ERROR;
1463
+ }
1464
+ return HttpStatus.valueOf(statusCode);
1465
+ }
1466
+
1467
+ }
1468
+ ----
1469
+
1470
+ In the example above, if `YourException` is thrown by a controller defined in the same package
1471
+ as `FooController`, a json representation of the `CustomerErrorType` POJO will be used instead
1472
+ of the `ErrorAttributes` representation.
1473
+
1443
1474
If you want more specific error pages for some conditions, the embedded servlet containers
1444
1475
support a uniform Java DSL for customizing the error handling. Assuming that you have a
1445
1476
mapping for `/400`:
0 commit comments