1. Introduction
1.绪论
Happy-path REST is pretty well-understood, and Spring makes this easy to do in Java.
Happy-path REST是很好理解的,Spring使其在Java中很容易做到。
But what about when things go wrong?
但当事情出错时怎么办?
In this tutorial, we’ll go over passing a Java exception as part of a JSON response using Spring.
在本教程中,我们将讨论使用Spring将Java异常作为JSON响应的一部分进行传递。
For a broader look, check out our posts on error handling for REST with Spring and creating a Java global exception handler.
如需更广泛的了解,请查看我们关于使用Spring的REST的错误处理和创建Java全局异常处理器的帖子。
2. An Annotated Solution
2.附加说明的解决方案
We’re going to use three basic Spring MVC annotations to solve this:
我们将使用三个基本的Spring MVC注解来解决这个问题。
- @RestControllerAdvice which contains @ControllerAdvice to register the surrounding class as something each @Controller should be aware of, and @ResponseBody to tell Spring to render that method’s response as JSON
- @ExceptionHandler to tell Spring which of our methods should be invoked for a given exception
Together, these create a Spring bean that handles any exceptions we configure it for. Here are more details about using @ControllerAdvice and @ExceptionHandler in conjunction.
这些一起创建了一个Spring Bean,可以处理我们配置的任何异常。这里有关于结合使用@ControllerAdvice和@ExceptionHandler的更多细节。
3. Example
3.例子
Firstly, let’s create an arbitrary custom exception to return to the client:
首先,让我们创建一个任意的自定义异常来返回给客户端。
public class CustomException extends RuntimeException {
// constructors
}
Secondly, let’s define a class to handle the exception and pass it to the client as JSON:
其次,让我们定义一个类来处理异常,并将其作为JSON传递给客户端。
@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler(CustomException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public CustomException handleCustomException(CustomException ce) {
return ce;
}
}
Note that we added the @ResponseStatus annotation. This will specify the status code to send to the client, in our case an Internal Server Error. Also, the @ResponseBody will ensure that the object is sent back to the client serialized in JSON. Finally, below is a dummy controller that shows an example of how the exception can be thrown:
注意,我们添加了@ResponseStatus 注释。这将指定发送至客户端的状态代码,在我们的例子中是内部服务器错误。此外,@ResponseBody将确保对象以JSON格式被发送回客户端。最后,下面是一个假的控制器,展示了一个如何抛出异常的例子。
@Controller
public class MainController {
@GetMapping("/")
public void index() throws CustomException {
throw new CustomException();
}
}
4. Conclusion
4.总结
In this post, we showed how to handle exceptions in Spring. Moreover, we showed how to send them back to the client serialized in JSON.
在这篇文章中,我们展示了如何在Spring中处理异常。此外,我们还展示了如何将它们以JSON的形式序列化地送回客户端。
The full implementation of this article can be found over on Github. This is a Maven-based project so it should be easy to import and run as it is.
本文的完整实现可以在Github上找到over。这是一个基于Maven的项目,所以应该很容易导入并按原样运行。