Skip to content

Commit cca153e

Browse files
committed
Document how to return custom JSON on errors
Closes gh-3999
1 parent 2663353 commit cca153e

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

spring-boot-docs/src/main/asciidoc/spring-boot-features.adoc

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1440,6 +1440,37 @@ is to handle `text/html` specifically and provide a fallback for everything else
14401440
just extend `BasicErrorController` and add a public method with a `@RequestMapping` that
14411441
has a `produces` attribute, and create a bean of your new type.
14421442

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+
14431474
If you want more specific error pages for some conditions, the embedded servlet containers
14441475
support a uniform Java DSL for customizing the error handling. Assuming that you have a
14451476
mapping for `/400`:

0 commit comments

Comments
 (0)