我第一次尝试使用Laravel异常处理。我需要的是捕获不同的异常时,我尝试连接到FTP服务器(例如。无法连接、用户/密码错误、无法找到新文件、无法打开文件)。我被卡住了,因为我看到Laravel已经有一个抛出异常的类(位于供应商/联盟/flysystem/src/Adapted/Ftp.php中)和Handler.php,但我不明白它们是如何协同工作的,以及如何根据异常呈现不同的消息。
非常感谢你的帮助。
发布于 2021-04-06 16:37:31
Handler.php将封装任何调用并处理任何扩展PHP本机类\Exception的异常。因此,无论异常在何处触发,处理程序都会尝试处理它。
您可以通过两种方式自定义响应。
try catch在处理程序之前捕获异常:基本上,使用
将可能触发异常的代码行括起来
try {
connectFTP();
} catch (\Exception $e) { //better use FilesystemException class in your case
//handle it
} 这里有两个ways:
Handler.php laravel 8.x (添加方法)
public function render($request, Exception $e)
{
if ($e instance of \FtpException) {
//handle it here
}
parent::render($request, $e);
}使用您自己的exception class: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,比如CSRF419异常和404页面未找到异常。
https://stackoverflow.com/questions/66964795
复制相似问题