Error Handling
Learn how you can use error handling mechanism defined in webservicescommons extension.
Overview
The webservicescommons extension was introduced with the Release 6.0.0. It includes several features, one of them being the error handling mechanism. The key benefits of this approach are as follows:
- Most errors return 400 - Bad Request by default, except basic errors, such as 404, 403, and 405.
- You can specify a status code for each exception using a Spring configuration (by a class name).
-
You can use additional attributes such as <reason>, <subjectType> and <subject>,by throwing an exception that extends WebserviceException (unchecked exception).
- You can create your own error converters to support custom validation objects, such as Spring errors.
RestHandlerExceptionResolver
- Defining the mapping between the response status code and the exception.
- Common error response format for all exceptions.
1. Mapping the Response Status Code and the Exception
Defining the mapping between the response status code and the exception is a key benefit. In addition, determining if the exception stack trace should be logged or not is also an advantage. Configuration properties are looked up in order, until the first one that applies is found. This is done through properties with the following format detailed below.
- extensionName is an extension name defined by RestHandlerExceptionResolver bean definition (propertySpecificKey field)
- exceptionName is a simple class name of the thrown exception
webservicescommons.resthandlerexceptionresolver.{extensionName}.{exceptionName}.logstack=true or false
webservicescommons.resthandlerexceptionresolver.{extensionName}.{exceptionName}.status=HTTP_STATUS_CODE
webservicescommons.resthandlerexceptionresolver.{exceptionName}.logstack=true or false
webservicescommons.resthandlerexceptionresolver.{exceptionName}.status=HTTP_STATUS_CODE
webservicescommons.resthandlerexceptionresolver.DEFAULT.logstack=true webservicescommons.resthandlerexceptionresolver.DEFAULT.status=400
Each property is treated separately. For example, an exception can have its status defined even when logstack is not defined. The default value is used in this case.
webservicescommons.resthandlerexceptionresolver.ycommercewebservices.CartAddressException.logstack=true webservicescommons.resthandlerexceptionresolver.ycommercewebservices.CartAddressException.status=400 webservicescommons.resthandlerexceptionresolver.CartAddressException.logstack=false webservicescommons.resthandlerexceptionresolver.CartAddressException.status=500
The properties with extension name and exception name are used. The logstack for exception is logged and a 400 HTTP status code is returned in response.
Common Error Response Formats
A list of ErrorWsDTO objects provides a common error response format for all exceptions. An exception is converted to ErrorWsDTO object with the help of the WebServiceErrorFactory. The JSON/XML format is created by HttpMessageConverters.
<bean id="abstractRestHandlerExceptionResolver" abstract="true">
<property name="webserviceErrorFactory" ref="webserviceErrorFactory" />
<property name="messageConverters" ref="messageConverters" />
</bean>
<bean id="restHandlerExceptionResolver" class="de.hybris.platform.webservicescommons.resolver.RestHandlerExceptionResolver"
parent="abstractRestHandlerExceptionResolver">
<property name="propertySpecificKey" value="xyzwebservices"/>
<property name="configurationService" ref="configurationService"/>
</bean>
RestExceptionResolver
The RestExceptionResolver class replaces the RestHandlerExceptionResolver. The RestExceptionResolver has two additional configuration properties:
- messageFormatterType: FORWARD or GENERIC
- message: generic exception message
The logic of looking up properties is the same as for the deprecated RestHandlerExceptionResolver class.
The response error message returned by WebServiceErrorFactory remains unchanged when messageFormatterType is set to FORWARD. Just as it remained unchanged for RestHandlerExceptionResolver.
Alternatively, if the messageFormatterType is set to GENERIC, then the value from the message property is set to response "error message".
webservicescommons.resthandlerexceptionresolver.DEFAULT.logstack=true webservicescommons.resthandlerexceptionresolver.DEFAULT.message=The application has encountered an error webservicescommons.resthandlerexceptionresolver.DEFAULT.messageFormatterType=FORWARD webservicescommons.resthandlerexceptionresolver.DEFAULT.status=400
This is an example configuration for the CartAddressException:
webservicescommons.resthandlerexceptionresolver.CartAddressException.logstack=false webservicescommons.resthandlerexceptionresolver.CartAddressException.messageFormatterType=GENERIC webservicescommons.resthandlerexceptionresolver.CartAddressException.status=500
The exception logstack is not logged for CartAddressException. A 500 HTTP status code is returned in response. The generic error message "The application has encountered an error" is returned for the default scope.
For other exceptions the logstack for an exception is logged and a 400 HTTP status code is returned in response. The error message returned by WebServiceErrorFactory remains unchanged in response.
<bean id="restHandlerExceptionResolver" class="de.hybris.platform.webservicescommons.resolver.RestExceptionResolver"
parent="wsBaseRestExceptionResolver">
<property name="webserviceErrorFactory" ref="webserviceErrorFactory" />
<property name="messageConverters" ref="messageConverters" />
<property name="extensionName" value="xyzwebservices" />
</bean>
The logic of looking up properties is defined as:
extensionName is extension name defined by RestExceptionResolver bean definition by extensionName field.
WebServiceErrorFactory
WebserviceErrorFactory is used in error handling mechanism to convert exceptions to ErrorWsDTO objects. Its default implementation DefaultWebserviceErrorFactory uses a list of AbstractErrorConverter in the conversion process. You have influence on how the exception will be converted to ErrorWsDTO object by adding your converter to that list when you define the factory in the web service extension web context.
Converters
The webservicescommons extension contains a base set of error converters.
By default, converters for the following types are provided:
| Error Converter | Supported Types | Supports Descendants |
|---|---|---|
| ValidationErrorConverter | org.springframework.validation.Errors | yes |
| WebserviceExceptionConverter | de.hybris.platform.webservicescommons.errors.converters.WebserviceException | yes |
| ExceptionConverter | java.lang.Exception excluding descendants of de.hybris.platform.webservicescommons.errors.converters.WebserviceException | yes |
Exceptions
The following sections describe exceptions available in the webservicescommons Extension.
WebserviceException
The WebserviceException is an exception that contains additional information about an error that has been thrown. To create it, you must extend the WebserviceException and provide information about the <type> of the error. Additionally, you can provide the <subjectType> and <subject> in order to expose other information, such as the product, entry, or any other object related to the error. You can also specify different <reasons> for the error as static Strings.
The following is an example of how to extend the WebserviceException:
/**
* Thrown when there is insufficient stock at a warehouse.
*/
public class LowStockException extends WebserviceException
{
public static final String NO_STOCK = "noStock";
public static final String LOW_STOCK = "lowStock";
private static final String TYPE = "InsufficientStockError";
private static final String SUBJECT_TYPE = "entry";
public LowStockException(final String message)
{
super(message);
}
public LowStockException(final String message, final String reason)
{
super(message, reason);
}
public LowStockException(final String message, final String reason, final String subject)
{
super(message, reason, subject);
}
@Override
public String getType()
{
return TYPE;
}
@Override
public String getSubjectType()
{
return SUBJECT_TYPE;
}
}
Usage
You can now throw the new custom exception:
throw new LowStockException("Product is currently out of stock", LowStockException.NO_STOCK, String.valueOf(entryNumber));
Response
The following JSON response is generated:
{
"errors" : [ {
"message": "Product is currently out of stock",
"reason": "noStock",
"subject": "1",
"subjectType": "entry",
"type": "InsufficientStockError"
} ]
}
WebserviceValidationException
Use the WebserviceValidationException to expose a list of errors, for example validation errors, as a single result. The required error converter is used to dynamically convert the validation object.
Implementation
You do not need to implement any new exceptions. You should always use the WebserviceValidationException, which takes one parameter, the <validationObject> parameter.
Usage
The following shows an example of throwing the Spring validation object org.springframework.validation.Errors:
formValidator.validate(form, errors);
if (errors.hasErrors())
{
throw new WebserviceValidationException(errors);
}
Converting Validation Objects
To convert a validation object into an error response, you need a proper error converter. The error converter must extend the AbstractErrorConverter and must support this specific object. Below you can find an example of the ValidationErrorConverter, defined in webservicescommons which converts errors:
/**
* Converts Spring's {@link Errors} to a list of {@link de.hybris.platform.ycommercewebservices.error.data.ErrorData}.
*/
public class ValidationErrorConverter extends AbstractErrorConverter
{
private static final String TYPE = "ValidationError";
private static final String SUBJECT_TYPE = "parameter";
private static final String REASON_INVALID = "invalid";
private static final String REASON_MISSING = "missing";
@Override
public boolean supports(final Class clazz)
{
return Errors.class.isAssignableFrom(clazz);
}
@Override
public void populate(final Object o, final List<ErrorData> webserviceErrorList)
{
final Errors errors = (Errors) o;
[..] // converting code here
webserviceErrorList.add(errorData);
}
}
Each error converter must be declared as a bean and added to the converter list in the webserviceErrorFactory in the ycommercewebservices-web-spring.xml:
<alias alias="webserviceErrorFactory" name="defaultWebserviceErrorFactory"/> <bean id="defaultWebserviceErrorFactory" class="de.hybris.platform.commercewebservicescommons.error.factory.impl.DefaultWebserviceErrorFactory"> <property name="converters"> <list> <ref bean="validationErrorConverter"/> <ref bean="cartModificationDataListErrorConverter"/> <ref bean="webserviceExceptionConverter"/> <ref bean="exceptionConverter"/> </list> </property> </bean>
Response
A response similar to the following is generated:
{
"errors" : [ {
"message" : "This field is required and must to be between 1 and 255 characters long.",
"reason" : "missing",
"subject" : "firstName",
"subjectType" : "parameter",
"type" : "ValidationError"
}, {
"message" : "This field is required and must to be between 1 and 255 characters long.",
"reason" : "missing",
"subject" : "lastName",
"subjectType" : "parameter",
"type" : "ValidationError"
}, {
"message" : "This field is required and must to be between 1 and 255 characters long.",
"reason" : "missing",
"subject" : "town",
"subjectType" : "parameter",
"type" : "ValidationError"
}, {
"message" : "This field is required and must to be between 1 and 10 characters long.",
"reason" : "missing",
"subject" : "postalCode",
"subjectType" : "parameter",
"type" : "ValidationError"
} ]
}