HttpProblems Helper
Zuplo encourages developers to build APIs with standard and actionable error messages. While any error format is supported, we default and encourage developers to adopt the Problem Details for HTTP APIs proposed standard format.
Developers can use the built-in HttpProblems
helper that's included with Zuplo
to build standard error messages in custom policies.
For example, using the helper to return an unauthorized error on a custom authentication policy can be done as follows.
ts
This will produce and error response in the standard format. Notice that trace information is included automatically. This makes it easy for users to report problems that can be searched in logs.
json
Available Methods
The HttpProblems
class provides static methods for all standard HTTP status
codes. Each method has the same signature:
typescript
Example Methods
Every status code has a corresponding method in the HttpProblems
class, so you
can use any HTTP status code as needed. Examples include:
ok()
- 200 OKbadRequest()
- 400 Bad Requestunauthorized()
- 401 UnauthorizednotFound()
- 404 Not Found
Method Parameters
All methods accept the same parameters:
- request:
ZuploRequest
- The incoming request object - context:
ZuploContext
- The Zuplo context object - overrides:
Partial<ProblemDetails>
(optional) - Custom values to override default problem details - additionalHeaders:
HeadersInit
(optional) - Additional headers to include in the response
Customizing Responses
You can customize the problem details by providing overrides:
typescript
Adding Custom Headers
You can add custom headers to the response:
typescript
HttpStatusCode Enum
The HttpStatusCode
enum provides numeric constants for all HTTP status codes:
typescript
See Also
- ProblemResponseFormatter
- Runtime Errors - Error handling with RuntimeError and ConfigurationError
The HttpProblems
helper supports most every
HTTP status code.
Some additional examples are shown.
ts
Overriding Property Values
Each method on the HttpProblems
object supports overriding the default values
of the problem response with custom values. The most common reason for this is
for setting the detail
value to something helpful for the end-user.
ts
Other properties like status
and title
can also be overridden, but make sure
to do so within the rules of the spec.
The most important thing to remember about problem details is that every
instance of a particular error should return the same value for title
. Details
about a specific error should go in the detail
property.
An example of how to correctly use the title
and detail
properties can be
demonstrated with an error that tells the user they provided an unexpected value
for a query parameter called take
that implements pagination. In this case,
the title
is always the same, but the detail
value changes to provide the
user with more detail about the error.
txt
ts
txt
ts
You can see how each of these cases help the user understand the problem, but
still provide the same title
.
Complete Method List
The HttpProblems
class provides static methods for all standard HTTP status
codes:
1xx Informational
continue()
- 100 ContinueswitchingProtocols()
- 101 Switching Protocolsprocessing()
- 102 Processing (deprecated)earlyHints()
- 103 Early Hints
2xx Success
ok()
- 200 OKcreated()
- 201 Createdaccepted()
- 202 AcceptednonAuthoritativeInformation()
- 203 Non-Authoritative InformationnoContent()
- 204 No ContentresetContent()
- 205 Reset ContentpartialContent()
- 206 Partial ContentmultiStatus()
- 207 Multi-StatusalreadyReported()
- 208 Already ReportedimUsed()
- 226 IM Used
3xx Redirection
multipleChoices()
- 300 Multiple ChoicesmovedPermanently()
- 301 Moved Permanentlyfound()
- 302 FoundseeOther()
- 303 See OthernotModified()
- 304 Not ModifieduseProxy()
- 305 Use ProxyswitchProxy()
- 306 Switch Proxy (deprecated)temporaryRedirect()
- 307 Temporary RedirectpermanentRedirect()
- 308 Permanent Redirect
4xx Client Errors
badRequest()
- 400 Bad Requestunauthorized()
- 401 UnauthorizedpaymentRequired()
- 402 Payment Requiredforbidden()
- 403 ForbiddennotFound()
- 404 Not FoundmethodNotAllowed()
- 405 Method Not AllowednotAcceptable()
- 406 Not AcceptableproxyAuthenticationRequired()
- 407 Proxy Authentication RequiredrequestTimeout()
- 408 Request Timeoutconflict()
- 409 Conflictgone()
- 410 GonelengthRequired()
- 411 Length RequiredpreconditionFailed()
- 412 Precondition FailedcontentTooLarge()
- 413 Content Too LargeuriTooLong()
- 414 URI Too LongunsupportedMediaType()
- 415 Unsupported Media TyperangeNotSatisfiable()
- 416 Range Not SatisfiableexpectationFailed()
- 417 Expectation FailedimATeapot()
- 418 I'm a teapotmisdirectedRequest()
- 421 Misdirected RequestunprocessableContent()
- 422 Unprocessable Contentlocked()
- 423 LockedfailedDependency()
- 424 Failed DependencytooEarly()
- 425 Too EarlyupgradeRequired()
- 426 Upgrade RequiredpreconditionRequired()
- 428 Precondition RequiredtooManyRequests()
- 429 Too Many RequestsrequestHeaderFieldsTooLarge()
- 431 Request Header Fields Too LargeunavailableForLegalReasons()
- 451 Unavailable For Legal Reasons
5xx Server Errors
internalServerError()
- 500 Internal Server ErrornotImplemented()
- 501 Not ImplementedbadGateway()
- 502 Bad GatewayserviceUnavailable()
- 503 Service UnavailablegatewayTimeout()
- 504 Gateway TimeouthttpVersionNotSupported()
- 505 HTTP Version Not SupportedvariantAlsoNegotiates()
- 506 Variant Also NegotiatesinsufficientStorage()
- 507 Insufficient StorageloopDetected()
- 508 Loop DetectednotExtended()
- 510 Not ExtendednetworkAuthenticationRequired()
- 511 Network Authentication Required
Additional Properties
It can sometimes be helpful to specify additional properties on the problem response. The problem specification requires a few specific fields, but allows for any additions as needed. For example, if we wanted to return an error to a user who was above their quote on creating widgets the error might look like this.
ts
Custom Headers
At times it can be useful to send custom headers with the error response. This can be done as shown below.
ts
If you want to set headers without any overrides just pass undefined
to the
third argument.
ts
HttpStatusCode Enum
For type-safe status code handling, use the HttpStatusCode
enum:
ts
The enum provides constants for all standard HTTP status codes, making your code more readable and less prone to typos.
See Also
- Policies - Building custom policies
- Runtime Errors - Error handling with RuntimeError and ConfigurationError
- Custom Request Handlers - Building request handlers