Customize exceptions

(Guillaume_tlse) #1


Sorry if my topic is not in the good sections.

I want to create a Custom class Exceptions, but i don’t find a good way to do it.

To be more specific, i want to send exception with differents properties like :

Exception report

- description: Info reported by back-end when an execption occurs
- properties:
– timestamp: datetime
– statusCode: number
– statusTxt: string
– exception: string
– message: string
– path: string

- description: Info reported by back-end when a bad request is received
- properties:
– timestamp: datetime
– code: number
– message: string
– path: string
- examples:
– badVersion:
— timestamp: 2018-07-11T07:56:24Z
— code: 0
— message: “bad version”
— path: “/v0/myprofile”

Is it possible ? How can i do this ?


(Basil) #2

Maybe this helps:

(Mmta41) #3

You can create & register your own exception handler and override renderException method:

namespace namespace\of\your;

use yii\web\Response;
use yii\web\NotFoundHttpException;

class ErrorHandler extends \yii\base\ErrorHandler

     * Renders the exception.
     * @param \Exception $exception the exception to be rendered.
    protected function renderException($exception)
        $response = \Yii::$app->has('response') ? \Yii::$app->response : new Response();
        $response->format = Response::FORMAT_JSON;
        if($exception instanceof NotFoundHttpException)
            $response->data = new BadRequestInfo();
           $response->data = new BackEndException();

then you can register your error handler in your api bootstrap:

$errorHandler = new namespace\of\your\ErrorHandler();

or change app config.php file components section:
‘errorHandler’ => [

(Guillaume_tlse) #4


Thanks very much mmta41 !
I’m going to try this today :slight_smile:


Edit : Ok it works perfectly ! Thanks again