无论开发接口还是开发其他项目,异常处理是必须的,虽然php有自带的异常处理机制,但如过每次处理都要try{}catch{}这会非常麻烦。好在php提供了 set_exception_handler 让开发者可以自定义异常处理。
还是回到此次的app接口开发实例中吧。在laravel中,所有没有通过 try{}catch{}抛出的异常都会走laravel的异常机制处理中的render方法。
下面就来写我们自己的自定义处理
首先自定义一个异常处理类:
<?php namespace App\Exceptions; use Throwable; class ApiException extends \RuntimeException { public function __construct(array $apiErrConst, Throwable $previous = null) { $code = $apiErrConst[0]; $message = $apiErrConst[1]; parent::__construct($message, $code, $previous); } }
自定义异常类的位置:
因为在laravel中,所有没有通过 try{}catch{}抛出的异常都会走laravel的异常机制处理中的render方法。因此,在定义好自己的异常处理类后只需要修改render方法即可:
public function render($request, Exception $exception) { // return parent::render($request, $exception); if ($exception instanceof ApiException){ $code = $exception->getCode(); $message = $exception->getMessage(); }else{ $code = $exception->getCode(); if (!$code || $code<0){ $code = ApiErrDesc::UNKNOWN_ERR[0]; } $message = $exception->getMessage() ?: ApiErrDesc::UNKNOWN_ERR[1]; } return $this->jsonData($code, $message); }
在使用时,直接用throw抛出就可以实现自定义异常处理了。
例如,我在验证用户信息时,如果返回的结果$res是false,就可以这样写:
if(!$res){ throw new ApiException(ApiErrDesc::ERR_PASSWORD); }
在抛出异常时只需带上错误类型就可以了,至于错误码和错误信息,都交给了自定义异常来获取处理。