Laravel9.x 自定义error Handling
在app/Exceptions目录下,新建ApiHandler自定义异常,用于返回json格式异常
<?php
namespace App\Exceptions;
use Exception;
use Throwable;
class ApiHandler extends Exception
{
/**
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = "", $code = 500, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
注册自定异常到app/Exceptions/Handler.php文件的register方法中
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
// 注册自定义ApiHandler
$this->renderable(function (ApiHandler $e) {
return response()->json(['message' => $e->getMessage()], $e->getCode());
});
$this->reportable(function (Throwable $e) {
//
});
}
在route/api.php路由下, 测试
Route::post('/test', function() {
throw new ApiHandler('test throw handler');
});