不管是预期或非预期,程序往往会发生一些错误,我们不希望使用者Call API或浏览网页的时候发生错误直接跳出像下面一样的错误讯息
如果太过详细的错误讯息可能会造成资安的危机,所以我们需要先把.env
中APP_DEBUG
的值改为False,如此一来我们看到的错误讯息会变成这样
接下来我们需要把这些错误讯息做处理,修改app\Exceptions\Handler
$this->renderable()
内部撰写闭包传入Exception和Request<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function(Exception $e, $request) {
return $this->handleException($request, $e);
});
}
/**
* Handle response from exception.
*
* @param Request $request
* @param \Exception $exception
* @return JsonResponse|null
*/
private function handleException($request, Exception $exception)
{
switch (true) {
case $exception instanceof NotFoundHttpException:
return response()->json([
'message' => 'Http not found.'
], 404);
case $exception instanceof MethodNotAllowedHttpException:
return response()->json([
'message' => 'Method not allowed.'
], 405);
case $exception instanceof UnauthorizedHttpException:
return response()->json([
'message' => 'Unauthorized.'
], 401);
}
return null;
}
}
改完後,再来试试我们的API
传入未知的route
预期的route,但是传入未定义的Method
预期的route和method,但身分验证错误
>>: 【程序】技术债 转生成恶役菜鸟工程师避免 Bad End 的 30 件事 - 11
上一篇, 我们已使用 xgboost 完成训练并且产生model档, 这个model的档名为bst_...
容器化是应用程序级别的虚拟化, 允许单个内核上有多个独立的用户空间实体, 而这些实体称为容器。 20...
最近睡太少身体开始亮红灯Orz 来逐步解剖一下Alpine initramfs的init scrip...
目前我最想先学习的程序语言是python,因为我现在大三在许多课程都会优先使用这个语言,如深度学习中...
大家好! 如果要深入查询一个多层物件,一般都是用 Object.keys 等方法,今天就是要简化这样...