HTTPError Struct
| Field | Type | Description |
|---|---|---|
Code | int | HTTP status code |
Message | string | Error message returned to client |
Err | error | Underlying error (for logging, not sent to client) |
Methods
Error Helpers
Convenient functions for common HTTP errors:BadRequest
400 Bad Request
Unauthorized
401 Unauthorized
Forbidden
403 Forbidden
NotFound
404 Not Found
Conflict
409 Conflict
InternalServerError
500 Internal Server Error
Usage
- BadRequest
- Forbidden
- NotFound
- Conflict
- InternalServerError
Creating Custom Errors
NewHTTPError
Create a custom HTTP error with any status code:NewHTTPErrorWithCause
Create an error with an underlying cause for debugging:errors.Unwrap():
Wrapping Errors
WrapError
Wrap an existing error with additional context:Error Checking
IsHTTPError
Check if an error is an HTTPError and extract it:Error Response Format
All HTTP errors are returned as JSON:| Status Code | Error Code |
|---|---|
| 400 | bad_request |
| 401 | unauthorized |
| 403 | forbidden |
| 404 | not_found |
| 409 | conflict |
| 500 | internal_server_error |
Custom Error Responses
For more control over error responses, usec.JSON() directly:
Error Handling Middleware
Create a centralized error handler:Best Practices
Use specific error messages
Use specific error messages
Do:Don’t:
Don't expose internal details
Don't expose internal details
Do:Don’t:
Use appropriate status codes
Use appropriate status codes
| Situation | Status Code |
|---|---|
| Invalid JSON body | 400 Bad Request |
| Missing required field | 400 Bad Request |
| Invalid field format | 400 Bad Request (or 422) |
| Missing/invalid auth | 401 Unauthorized |
| Valid auth, no permission | 403 Forbidden |
| Resource doesn’t exist | 404 Not Found |
| Resource already exists | 409 Conflict |
| Server error | 500 Internal Server Error |
| Service unavailable | 503 Service Unavailable |
Log underlying errors
Log underlying errors