Handling application level errors

There are many situations in which you need to notify an error to a client using your REST Web service.

Errors in calls to Web services may occur for various reasons; for example:
  • the user input is incorrect
  • the resource does not exist
  • the server response failed
  • the client does not have access to the resource
  • the database connection failed
In these cases, you normally return an HTTP status code in the range 400 to 599 with its default message. The most common ones you encounter are as follows:
  • client (400-499)
    • 400 Bad Request
    • 401 Unauthorized
    • 403 Forbidden
    • 404 Not Found
  • server (500-599)
    • 500 Internal Server Error
    • 501 Not Implemented

For information on the full range of HTTP status codes see RFC 2616.

There are some situations where it is more useful to describe the error specifically, and in your REST function you can use the error handling attributes for this purpose.

Handling errors with attributes

In GWS REST you can perform error handling using two attributes:
  • with the WSThrows attribute, set on the ATTRIBUTES() clause of the function, you list errors that may be encountered accessing a resource. From this the client stub generated from the OpenAPI specification, handles the error corresponding to those HTTP status codes.
  • with the WSError attribute, set on a public variable defined at the modular level, you can provide a description of the status-code when an error is encountered at runtime to replace the standard HTTP status code description.

In your function, you code to trap an error at runtime with a call to the SetRestError() method, to return the HTTP status code and a description to the client.

Publishing errors

When you generate the service description, the errors you declared in the WSThrows attribute, the code reference and the error detail, are published in the "responses" section for that function in the OpenAPI specification file. The modular variables declared with WSError attribute are found in the "component" section at the end of the specification file.