在APP开发的时候,经常会遇到因为服务端报错而接口挂掉的情况.作为开发者要避免出现这样情况.除了严格对接口的输入输出做控制,也要对异常处理类进行扩展,从而达到完美避免接口挂掉的情况.
以下是基于Laravel框架的异常处理扩展.一旦出现异常情况,就发邮件给管理员,从而及时查看.
//目录app/Exception/Hander.php
public function render($request, Exception $e) {
if ($e instanceof ModelNotFoundException) {
$e = new NotFoundHttpException($e->getMessage(), $e);
}
if ($request->is('api/*')) {
if ($e instanceof NotFoundHttpException) {
return response(AjaxCallbackMessage('请求接口不存在!', false), 404);
}
$key = md5($request->fullUrl());
if (\App::environment() === 'production' && !(\Cache::has($key) ? \Cache::get($key) : false)) {
//发送短信提醒
//SendSMS(18058190409, '接口:'.$request->fullUrl().'异常!', 'interface_exception');
\Cache::put($key, true, 30);
if (!$e instanceof \Symfony\Component\Debug\Exception\FlattenException) {
$e = \Symfony\Component\Debug\Exception\FlattenException::create($e);
}
$exception = new \Symfony\Component\Debug\ExceptionHandler();
$content = $exception->getContent($e);
$css = $exception->getStylesheet($e);
\Mail::queue('errors.api.mail', ['url' => $request->fullUrl(), 'request' => $request->all(), 'content' => $content, 'css' => $css], function ($message) {
$message->to('xihuan@tyrbl.com')
->cc('zhangyl@tyrbl.com')
->subject('商圈接口异常');
});
}
return response(AjaxCallbackMessage('服务器累了,稍后再试!', false));
}
return parent::render($request, $e);
}
网友评论