Can you treat errors as resources in a RESTful API?
My question is around error handling with a RESTful API. Traditionally people have used error codes and messages in the response body. My question is can you formulate those errors into full fledged resources. For example you might want to get the error as an HTML page or get a list of possible errors in json format. It seems quite natural for an error to be a resource.
However it seems a bit dirty to return a "resource" as an error for another resource but if you think about it an error code and an error message in the request body is just that without the extra useful semantics of a resource.
Also to be clear this shouldn't be a subjective question. I want to know if doing this would violate RESTful design principles or any notable relevant RFC for HTTP communication.
Edit:
One issue is the need to differentiate between error types and error instances. It pretty useful to have error types as resources but capturing every possible error instance and reporting that back isn't as useful.
Edit2:
The core of the question is if an error resource (different resource than requested) should be put in the 4XX/5XX response body. The question about if 200 + error or 4XX/5XX should handle errors is answered over here:REST API error return good practices
While you most certainly can represent an error as a resource, your major issue will be that clients are going to find it hard to understand the error as an error; they'll interpret a success return code as an overall success. That's Wrong! (We've had a problem with this in one of the web applications at work, which handled errors by sending back a 200 with a document that had one of its fields saying that there was an error. It was a complete pain in the neck to deal with. Once we switched to using real error codes, clients worked much better.)
To mitigate against this, return JSON descriptions with your errors (payloads for the 4** and 5** messages) that describe where the resource containing further information is; the errors are still errors, but now they're errors with rich hyperlinked information. That's RESTful and actually pretty nice! You probably also ought to have some way for clients to discover these error resources that they ought to know about via other mechanisms, eg, a /previous-errors
resource that lists the ones that they're authorised to see. After all, discoverability is a good REST principle too; the state should be the state of resources (as much as possible) and as little as possible should need to be stored in clients.