Skip to content

Commit 7fd3e48

Browse files
committed
docs(readme): document custom error usage
1 parent 70b273a commit 7fd3e48

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ JsonApiDotnetCore provides a framework for building [json:api](http://jsonapi.or
2727
- [Sorting](#sorting)
2828
- [Meta](#meta)
2929
- [Client Generated Ids](#client-generated-ids)
30+
- [Custom Errors](#custom-errors)
3031
- [Tests](#tests)
3132

3233
## Comprehensive Demo
@@ -364,6 +365,38 @@ services.AddJsonApi<AppDbContext>(opt =>
364365
});
365366
```
366367

368+
### Custom Errors
369+
370+
By default, errors will only contain the properties defined by the internal [Error](https://github.com/Research-Institute/json-api-dotnet-core/blob/master/src/JsonApiDotNetCore/Internal/Error.cs) class. However, you can create your own by inheriting from `Error` and either throwing it in a `JsonApiException` or returning the error from your controller.
371+
372+
```chsarp
373+
// custom error definition
374+
public class CustomError : Error {
375+
public CustomError(string status, string title, string detail, string myProp)
376+
: base(status, title, detail)
377+
{
378+
MyCustomProperty = myProp;
379+
}
380+
public string MyCustomProperty { get; set; }
381+
}
382+
383+
// throwing a custom error
384+
public void MyMethod() {
385+
var error = new CustomError("507", "title", "detail", "custom");
386+
throw new JsonApiException(error);
387+
}
388+
389+
// returning from controller
390+
[HttpPost]
391+
public override async Task<IActionResult> PostAsync([FromBody] MyEntity entity)
392+
{
393+
if(_db.IsFull)
394+
return new ObjectResult(new CustomError("507", "Database is full.", "Theres no more room.", "Sorry."));
395+
396+
// ...
397+
}
398+
```
399+
367400
## Tests
368401

369402
I am using DotNetCoreDocs to generate sample requests and documentation.

0 commit comments

Comments
 (0)