Support the ongoing development of Laravel.io →
Requests Architecture
Last updated 2 years ago.
0

first you need to make some changes in the App\Exceptions\Handler

public function render($request, Exception $e)
{
    if ($e instanceof MyException) {
        return response()->json(['exception' => get_class($e), 'message' => $e->getMessage(), 'errors' => $e->getErrors()], 400);
    }

     return parent::render($request, $e);
}

Now you need your own exception class

class MyException extends RuntimeException
{

    private $errors;

    public function __construct($message, $code = 0, Exception $previous = null, $errors = []) 
    {
        parent::__construct($message, $code, $previous);

        $this->errors = $errors; 
    }

    public function getErrors() 
    { 
        return $this->errors; 
    }
}

usage

throw new MyException('exception occured', $errorCode, null, $errorsArray);
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.