Customize exceptions


(Guillaume_tlse) #1

Hello,

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

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

BadRequestInfo:
- 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 ?

Thanks


(Basil) #2

Maybe this helps: https://www.yiiframework.com/doc/guide/2.0/en/rest-error-handling#customizing-error-response


(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();
        }else{
           $response->data = new BackEndException();
        }
        $response->send();
     }
}

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

$errorHandler = new namespace\of\your\ErrorHandler();
$app->set('errorHandler',$errorHandler);
$errorHandler->register();

or change app config.php file components section:
‘errorHandler’ => [
'class'=>'namespace\of\your\Errorhandler'
],


(Guillaume_tlse) #4

Hello,

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

Cya

Edit : Ok it works perfectly ! Thanks again