Book Image

Building RESTful Web Services with Spring 5 - Second Edition

By : Raja CSP Raman, Ludovic Dewailly
Book Image

Building RESTful Web Services with Spring 5 - Second Edition

By: Raja CSP Raman, Ludovic Dewailly

Overview of this book

REST is an architectural style that tackles the challenges of building scalable web services. In today's connected world, APIs have taken a central role on the web. APIs provide the fabric through which systems interact, and REST has become synonymous with APIs.The depth, breadth, and ease of use of Spring makes it one of the most attractive frameworks in the Java ecosystem. Marrying the two technologies is therefore a very natural choice.This book takes you through the design of RESTful web services and leverages the Spring Framework to implement these services. Starting from the basics of the philosophy behind REST, you'll go through the steps of designing and implementing an enterprise-grade RESTful web service. Taking a practical approach, each chapter provides code samples that you can apply to your own circumstances.This second edition brings forth the power of the latest Spring 5.0 release, working with MVC built-in as well as the front end framework. It then goes beyond the use of Spring to explores approaches to tackle resilience, security, and scalability concerns. Improve performance of your applications with the new HTTP 2.0 standards. You'll learn techniques to deal with security in Spring and discover how to implement unit and integration test strategies.Finally, the book ends by walking you through building a Java client for your RESTful web service, along with some scaling techniques using the new Spring Reactive libraries.
Table of Contents (21 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
6
Spring Security and JWT (JSON Web Token)
Index

Error handling


So far in our application, we haven't defined any specific error handler to catch the error and convey it to the right format. Usually when we deal with an unexpected situation in REST APIs, it will automatically throw an HTTP error such as 404. Errors such as 404 will show explicitly in the browser. This is fine normally; however, we might need a JSON format result regardless of whether things go right or wrong.

Converting the error into JSON format would be a nice idea in such cases. By providing the JSON format, we can keep our application clean and standardized.

Here, we will discuss how to manage errors and display them in JSON format when things go wrong. Let's create a common error handler class to manage all of our errors:

public class ErrorHandler {
  @ExceptionHandler(Exception.class)
  public @ResponseBody <T> T handleException(Exception ex) {    
    Map<String, Object> errorMap = new LinkedHashMap<>();
    if(ex instanceof org.springframework.web...