Laravel 任意位置响应请求,自定义接口异常处理类
1.创建文件 app\Exception\ApiException.php
<?php
namespace App\Exceptions;
class ApiException extends \Exception
{
function __construct($errorMsg='', $errorCode = 500)
{
$this->errorMsg = $errorMsg;
$this->errorCode = $errorCode;
parent::__construct($errorMsg);
}
}
2.修改 app\Exception\Handler.php
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
// return parent::render($request, $exception);
// 如果config配置debug为true ==>debug模式的话让laravel自行处理
// if(config('app.debug')){
// return parent::render($request, $exception);
// }
if($exception instanceof ApiException) {
return $this->handle($request, $exception);
}else{
return parent::render($request, $exception);
}
}
// 新添加的handle函数
public function handle($request, Exception $e){
// 只处理自定义的APIException异常
if($e instanceof ApiException) {
$result = [
"msg" => $e->errorMsg,
"code" => $e->errorCode
];
return response()->json($result);
}
return parent::render($request, $e);
}
使用
任意位置
if(empty($row)){
throw new ApiException('规格不存在','201');
}