如何在Laravel中获取没有HTML的原始异常消息?

Kam*_*dov 7 php ajax exception laravel

我向Laravel后端发出ajax请求.

在后端,我检查请求数据并抛出一些例外.默认情况下,Laravel会生成带有异常消息的html页面.

我想回复原始异常消息而不是任何HTML.

->getMessage()不起作用.Laravel一如既往地生成html.

我该怎么办?

Lim*_*nte 15

在Laravel 5中,您可以通过编辑render方法来捕获异常app/Exceptions/Handler.php.

如果要捕获所有AJAX请求的异常,可以执行以下操作:

public function render($request, Exception $e) 
{
    if ($request->ajax()) {
        return response()->json(['message' => $e->getMessage()]);
    }

    return parent::render($request, $e);
}
Run Code Online (Sandbox Code Playgroud)

这将应用于AJAX请求中的任何异常.如果您的应用发送了例外情况App\Exceptions\MyOwnException,请检查该实例.

public function render($request, Exception $e)
{   
    if ($e instanceof \App\Exceptions\MyOwnException) {
        return response()->json(['message' => $e->getMessage()]);
    }

    return parent::render($request, $e);
}
Run Code Online (Sandbox Code Playgroud)

  • @KamilDavudov使用[来源](https://github.com/illuminate/routing/blob/master/ResponseFactory.php#L83):)只需添加第二个参数,例如`response() - > json($ data, 400)` (2认同)