Laravel 自定义异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52430451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:04:33  来源:igfitidea点击:

Laravel custom exception

phplaravelexceptionlaravel-5laravel-exceptions

提问by Rahul

Before posting this question I have searched internet for appropriate answers but got none.These are my following questions:

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

1) How to throw exception without try catch in laravel controller and get exception in the view of the called controller. Example : TestController.php

1) 如何在laravel 控制器中不使用try catch 抛出异常并在被调用控制器的视图中获取异常。 示例:TestController.php

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

How to get exception message in dashboard view

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

2) How to set format for exception message, suppose I want to return format as

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

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

I have created a custom exception but don't know how to use it to fully

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

<?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);
        }
    }

}

回答by Marcin Orlowski

All uncaught exceptions are intercepted by default exceptions handler. If you want this to behave differently, you just need to modify it: https://laravel.com/docs/5.7/errors#the-exception-handler

默认异常处理程序会拦截所有未捕获的异常。如果你想让它表现得不同,你只需要修改它:https: //laravel.com/docs/5.7/errors#the-exception-handler

回答by Marcin Nabia?ek

Answering your questions:

回答您的问题:

  1. To pass this exception to view, you can implement rendermethod what you already started to do. You can just do:

    if(!$request->ajax()){
        view('error_handler', compact('exception'))
    } else {
       return response()->json($response);
    }
    
  1. 要将这个异常传递给查看,你可以实现render你已经开始做的方法。你可以这样做:

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

so now you can just create error_handler.blade.phpview and you will have access in there to $exceptionvariable, so you can use in there {{ $exception->getMessage}}and so on

所以现在你可以创建error_handler.blade.php视图,你将可以在那里访问$exception变量,所以你可以在那里使用{{ $exception->getMessage}}等等

  1. You didn't define what exactly you want to achieve, however it should work without any problem:

    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'
              ]);
    
    }
    
  1. 您没有定义您想要实现的确切目标,但是它应该可以正常工作:

    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'
              ]);
    
    }
    

Of course instead of using $exception->getCode()for codeyou can put anything you want, this is just an example that you can also use code and message that you have in your exception assuming you set some custom when you throw exception for example:

当然,除了使用$exception->getCode()forcode你可以放任何你想要的东西,这只是一个例子,你也可以使用你在异常中的代码和消息,假设你在抛出异常时设置了一些自定义,例如:

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

回答by Yves Kipondo

There isn't realy reason to thrown an exception if your purpose is to show the message of that exception within the view which is rendered by the controller. And It isn't a best way to manage exception, because by default all exception which are throw are handle and catch within the App\Exceptions\Handlerclass.

如果您的目的是在控制器呈现的视图中显示该异常的消息,则没有真正的理由抛出异常。并且它不是管理异常的最佳方法,因为默认情况下,所有抛出的异常都是在App\Exceptions\Handler类中处理和捕获的。

I think you know exactly when that type of CustomExption you have create will be thrown, but instead of throwing that error just traite that error which need an exception in different way without exception. For that you can create an Array in which old code, status, message, data and pass it to the view method;

我认为您确切地知道您创建的那种类型的 CustomExption 何时会被抛出,但与其抛出该错误,不如只抛出该错误,该错误需要以不同的方式毫无例外地抛出异常。为此,您可以创建一个数组,其中包含旧代码、状态、消息、数据并将其传递给视图方法;

class CustomController extends Controller
{
    public function samemethod(){
         // some code that can generate an error

         // construct the error data
         $customErrorData = [
             'code' => 0000,
             'status' => "some status",
             'message' => "Some error message",
             'data' => [...]
         ];

         // After error data creation you can pass it to the view
         return View::make('customview', compact('customErrorData'));
    }
}

You have you error data in your view

您的视图中有错误数据