php - Laravel 自定义异常

标签 php laravel exception laravel-5 laravel-exceptions

在发布此问题之前,我已在互联网上搜索适当的答案,但没有找到。这些是我的以下问题:

1) 如何在 Laravel Controller 中不使用 try catch 抛出异常,并在被调用 Controller 的 View 中获取异常。 示例:TestController.php

function index(){
throw new CustomException('Data not found');
return view('dashboard');
}

如何在仪表板 View 中获取异常消息

2)如何设置异常消息的格式,假设我想返回格式为

$response['code'] = 0;
        $response['status'] = 'error';
        $response['message'] = 'message';
        $response['data'] = '';

我创建了一个自定义异常,但不知道如何充分使用它

<?php

namespace App\Exceptions;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Mockery\Exception;

class CustomException extends Exception{

    public $response;


    /**
     * Report the exception.
     *
     * @return void
     */
    public function report()
    {
    }

    /**
     * Render the exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request,$exception){
        ob_clean();
        $response['code'] = 0;
        $response['status'] = 'error';
        $response['message'] = 'Message';
        $response['data'] = '';
        if(!$request->ajax()){
            // non ajax response
        }else{
            return response()->json($response);
        }
    }

}

最佳答案

回答您的问题:

  1. 要将此异常传递给 View ,您可以实现您已经开始执行的 render 方法。你可以这样做:

    if(!$request->ajax()){
        view('error_handler', compact('exception'))
    } else {
       return response()->json($response);
    }
    

现在您只需创建 error_handler.blade.php View ,您就可以在其中访问 $exception 变量,因此您可以在其中使用 {{ $exception->getMessage}} 等等

  • 您没有定义您到底想要实现什么,但它应该可以毫无问题地工作:

    public function render($request,$exception) {
    
        if(!$request->ajax()){
            view('error_handler', compact('exception'))
        }
    
        return response()->json([
                  'code' => $exception->getCode(),
                  'status' => 'error',
                  'message' => $exception->getMessage(),
                  'data' => 'sample data'
              ]);
    
    }
    
  • 当然,您可以放置​​任何您想要的内容,而不是使用 $exception->getCode() 作为 code,这只是一个示例,您也可以使用 code 和假设您在引发异常时设置了一些自定义,则异常中的消息例如:

    throw new CustomException('This is custom message', 123);
    

    关于php - Laravel 自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52430451/

    相关文章:

    javascript - 将 bootstrap 模态值传递到 php

    php - 向所有订阅者(所有用户)发送电子邮件 PHP 和 MYSQL(每天 25,000 封邮件)

    mysql - 如果具有相同的日期,如何使用 foreach 并隐藏其他结果?

    java - 将数据存储在自定义检查异常中是一个坏主意吗?

    php - ASP 与 PHP 编译

    php - 从 View 中的外键获取数据(Laravel 5.6)

    php - Laravel - 从 View 中调用 Redirect::to()

    c++ - 信号(): any performance impact?

    javascript - 你如何在 Javascript 中抛出自定义错误类?

    php - 为用户 GAE 自动化通配符子域