0

Currently in a package, it has HttpException exception

namespace DigitalOceanV2\Exception;

class HttpException extends \RuntimeException implements ExceptionInterface
{

}

Is there a way to to convert it Laravel HttpResponseException uses without touching that exception from the package?

2 Answers 2

2

You can catch that exception and rethrow it.

In your app/Exceptions/Handler.php file.

public function render($request, Exception $exception)
{
    if ($exception instanceof \DigitalOceanV2\Exception) {
        throw new HttpResponseException;
    }

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

Edit: I haven't tested this but according to the exception class. You can pass a response as a parameter to the constructor. So you should be able to do this:

$response = response($exception->getMessage());
throw new HttpResponseException($response);
Sign up to request clarification or add additional context in comments.

4 Comments

Will it pass the message to HttpResponseException ?
Yes, it will add the message automatically.
@Jeff thanks for the Answer. Just wondering if there a way to return json response via HttpResponseException?
Instead of rethrowing the exception, you can simply return a response from the render() method. E.g. if ($e instance of Exception) { return response(['json' => 'data']); }
0

Maybe this is late, but at least on Laravel 8+ there is a \App\Exceptions\Handler::report method that I think would be more appropriate to override and put such logic - e.g. converting the exception to a different/custom class.

In fact render suggests how to render it, not what to do with it.

public function report(Throwable $e)
{
    if ($e instanceof \DigitalOceanV2\Exception) {
        throw new HttpResponseException;
    }

    return parent::report($e);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.