dingo / dingo/api

[Question] Exception with Custom Attributes

Open
#1,080 7 comments 0 reactions 0 assignees View on GitHub
discussion
Dominant language
PHP
Stars
9.4k
Forks
1.3k
PR merge metrics
No merged PRs in 30d

Description

Dear all,

first of all: thanks a lot for this awesome package! I really love it - keep your work up :)

However, I have a question regarding the Exception Handling, specifically how to add custom fields to exceptions. I would like to make the exceptions thrown JsonAPI-valid ([JSON API Errors](http://jsonapi.org/format/#errors)). I have googled a lot on this problem and tracked down a lot of issues on this project site as well. However, I was not able to solve my problem.

First of all, I have adapted the `api.php` config file, specifically the `errorFormat` to meet my demands.

Then I have created an `ApiBaseException` extending the `Symfony\Component\HttpKernel\Exception\HttpException` as described in the Wiki Pages ([Errors and Error Responses](https://github.com/dingo/api/wiki/Errors-And-Error-Responses))

The constructor for this Exception looks like this:

``` php
public function __construct(..., $title = null, $meta = []) {
parent::__construct(..., ..., ...);
$this->title = $title;
$this->meta = $meta;
}
```

because i would like to add the fields `title` and `meta` to my JSON Exception. For example, the result should look like this:

``` json
{ "errors" : {
"message" : "The Element could not be stored to the database!",
"code" : "INTERNAL CODE",
"status" : 500,
"title" : "ELEMENT_SAVE_ERROR",
"meta" : {
"more" : "information",
"further" : "data"
}
} }
```

However, if I throw the exception like this `throw new ApiBaseException(..., ..., ..., "ELEMENT_SAVE_ERROR", []);` within the controller this further information (e.g., `title` and `meta`) is not displayed.

It looks to me, that all information (except the default values provided in the original `api.php` config file) are omitted. How can I add the additional fields to the JSON Response for exceptions?

I would highly appreciate your answer or contributions to solve my problem. Please let me know, if you need any other information.

Kind regards,

Johannes

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.