Handler.php 将封装任何调用并处理任何扩展 PHP 原生类 \Exception 的异常。所以,无论异常在哪里触发,handler都会尝试去处理。
您可以通过两种方式自定义响应。
- 在处理程序之前捕获异常:
基本上,用 try catch 包围可以触发异常的代码行
try {
connectFTP();
} catch (\Exception $e) { //better use FilesystemException class in your case
//handle it
}
- 补丁:只需在渲染方法中拦截有问题的异常
Handler.php laravel 8.x(添加方法)
public function render($request, Exception $e)
{
if ($e instance of \FtpException) {
//handle it here
}
parent::render($request, $e);
}
- 使用你自己的异常类:More info here
class FtpConnectionException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function render($request)
{
return response(...);
}
}
在 Vendor 文件夹中触发异常时,如何使用自己的异常类?使用 try catch 方法
try {
connectFTP();
} catch (\Exception $e) { //better use FilesystemException class in your case
throw new FtpConnectionException($e->getMessage(), $e->getCode(), $e->getPrevious());
}
注意:一些异常不会到达 Handler.php,例如 CSRF 419 异常和 404 页面未找到异常。