در حال بارگذاری ...

Defining Custom Exceptions0:00

We can now catch multiple exception types using the pipe operator. Let's create a couple. Let's say we have a ChargeRejectedException. And then we'll have another one for, how about, NotEnoughFundsException? So yeah, if you bill a User, these two exceptions can be thrown. Let's set up a quick User here, subscribe. And for now I'm just going to var_dump subscribing. Okay, so yeah, in your controller or wherever this might be, you might use a try-catch. And you might say, try, with my User, to subscribe them. But catch, in this case, a ChargeRejectedException. But also I want to handle the situation that we don't have enough funds. And often you'll find that you need to handle those in the exact same way.

Catching Multiple Types1:19

if two different exception types are thrown. Now, if we were to run this, it's going to work anywhere. So with php 7.0, we get subscribing. But of course, if I throw a new ChargeFailedException or ChargeRejectedException, we catch that. And if we say NotEnoughFundsException, we catch that as well. However, in php 7.1, we can merge these. So I could say catch a ChargeRejectedException or a NotEnoughFundsException, and then handle them like so. That removes the duplication. But yeah, it's not going to work in 7.0. So if I run this, we will get a syntax error.

PHP 7.1 Pipe Catch1:48

That removes the duplication. But yeah, it's not going to work in 7.0. So if I run this, we will get a syntax error. But again, if I switch over to 7.1, and we give it a shot, no exception will be thrown. So that's all you need to know. If you need to catch multiple exception types and handle them in the exact same way, the pipe is exactly what you want.

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟