Skip to main content

Custom Error Messages

Custom Error Messages feature allows you to customize error responses of HTTP requests by providing a static string against HTTP error codes. Through this feature, you can add meaningful information to a failed API call. For example, instead of a 400 Bad Request error response, you can customize it to say 400 Bad request due to invalid request message framing.

note

These are static messages. To define dynamic messages that provide more meaningful information at runtime, please see the Dynamic Error Messages feature.

Configure Custom Error Messages

Error messages are customized through the description field of an OAS response object. You can customize HTTP response codes through this field in your OpenAPI specification as shown below.

  • The following example shows how to customize an error message against an HTTP error code.
OpenAPI v3.0
"responses": {
"412": {
"description": "Precondition to make the request failed"
}
}
note

This feature doesn't support defining a custom response for an entire code range. Please see Configure Response Messages for an Error Group in Dynamic Error Messages.

  • The following example shows how you can add a custom type in addition to customizing messages of error status codes.
OpenAPI v3.0
"responses": {
"412": {
"description": "Precondition to make the request failed",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/NestedModelException"
}
}
}
}
}
note

Please note that the custom type you mention here, i.e. NestedModelException in this case, should already be defined in the custom types. Otherwise your API specification file will not pass validation.

After configuring a custom error response as follows:

OpenAPI v3.0
"responses": {
"404": {
"description": "Call failed because the accessed page is not found."
}
}

Once you have configured custom error messages, you can catch the response in the API call.

try
{
petsController.CreatePet(pet);
}
catch (ApiException exception)
{
// Printing the error message
Console.WriteLine(exception.Message);
}

APIMatic generated SDK will surface the following message every time an API call fails with 404 error code:

ApiException: Call failed because the accessed page is not found.