A PHP library for handling errors withouttry andcatch blocks.
composer require might-fail/might-fail
ImportmightFail function into your source files.
usefunctionMightFail\mightFail;
Requesting data from an API in a laravel application.
Here's the try-catch way to do it.
try {$response = Http::withToken($secretToken)->post('https://example.com')->throw();$json =$response->json();if ($json ===null) {returnresponse()->json(['error' =>'Invalid JSON.']); }returnresponse()->json($json);}catch (ConnectionException$e) {returnresponse()->json(['error' =>'Connection failed.']);}catch (TimeoutException$e) {returnresponse()->json(['error' =>'Timeout.']);}catch (HttpException$e) {returnresponse()->json(['error' =>'HTTP error.']);}catch (Exception$e) {returnresponse()->json(['error' =>'Unknown error.']);}And, here's themightFail way to do it.
usefunctionMightFail\mightFail;$either =mightFail(fn () => Http::withToken($secretToken)->post('https://example.com')->throw());// You can also destructure the object like a tuple, if you want.[$error,$response] =$either;if ($either->error) {returnmatch (get_class($either->error)) { ConnectionException::class =>response()->json(['error' =>'Connection failed.']), TimeoutException::class =>response()->json(['error' =>'Timeout.']), HttpException::class =>response()->json(['error' =>'HTTP error.']),default =>response()->json(['error' =>'Unknown error.']), };}$response =$either->result;$either =mightFail(fn () => User::findOrFail(1));if ($either->error !==null) {returnresponse()->json(['error' =>'User not found.', ]);}Calling a repository method that might fail.
Here's the classic try-catch way to do it.
try {$shop = ShopRepository::visit($id);returnresponse()->json(['success' =>true,'data' =>$shop, ]);}catch (Exception$e) {returnresponse()->json(['error' =>'Could not visit this shop', ]);}finally {logger()->info('User tried to visit a shop', ['shop' =>$shop,// ... ]);}And, here's themightFail way to do it.
usefunctionMightFail\mightFail;[$error,$shop] =mightFail(fn () => ShopRepository::visit($id));// Your finally blocklogger()->info('User tried to visit a shop', ['shop' =>$shop,// ...]);// Guard against error and handle it immediatelyif ($error !==null) {returnresponse()->json(['error' =>'Could not visit this shop', ]);}// Now we can safely return the shopreturnresponse()->json(['success' =>true,'data' =>$shop,]);You can returnMight orFail classes from a method and natively return anEither type withoutmightFailfunction.
useMightFail\Either;useMightFail\Fail;useMightFail\Might;publicfunctionvisit(int$id):Either{// ...if ($badThingHappened) {return Fail::from(newException('Something went wrong.')); }return Might::from($shop);}