Book Image

Building a RESTful Web Service with Spring

By : Ludovic Dewailly
Book Image

Building a RESTful Web Service with Spring

By: Ludovic Dewailly

Overview of this book

Table of Contents (17 chapters)
Building a RESTful Web Service with Spring
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Exception handling


Chapter 3, The First Endpoint, touched upon defining a consistent response format including error codes and error descriptions. The corollary on the client side is to define an exception that encapsulates information about why a particular call failed. We could, therefore, define the following exception:

public class ClientException extends RuntimeException {

  private final int errorCode;
  private final String errorDescription;

  public ClientException(ApiError error) {
    super(error.getErrorCode() + ": " + error.getDescription());
    this.errorCode = error.getErrorCode();
    this.errorDescription = error.getDescription();
  }

  public int getErrorCode() {
    return errorCode;
  }

  public String getErrorDescription() {
    return errorDescription;
  }
}

Clients consuming a RESTful web service with such exception handling will have a consistent way to manage and report errors. There are, however, a few situations where generic exception handling requires more...