I've created a file upload method and the file uploading with the file extension like jpg, png etc are successful. However, when I upload a zip file, it says me "Undefined variable: e". To find, I did dd() at the beginning of the respective method but it still says the above error. My route is as below:
Route::post('media/savedata/{id?}/{page?}', 'Administrator\MedialibraryController#savedata');
The method is as below:
public function savedata($id, $page, Request $request) {
...
}
The content of the "network" tab is as below:
Request URL: http://localhost/stmd/administrator/media/savedata/0/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
------WebKitFormBoundaryaHtERzAAThbQB4ae
Content-Disposition: form-data; name="_token"
TXLvBGRXrdjpQbhAjm18MTxkiHamauvcjhKBhl6n
------WebKitFormBoundaryaHtERzAAThbQB4ae
Content-Disposition: form-data; name="fileType"
I
------WebKitFormBoundaryaHtERzAAThbQB4ae
Content-Disposition: form-data; name="fileName"; filename="gradle-3.5-bin.zip"
Content-Type: application/zip
My intention is: If zip file is upload then it will redirect to another page however, I can't do this because even dd() is not working.
UPDATE:
Below is the Laravel Log:
[2018-07-23 11:59:51] local.ERROR: Undefined variable: e {"exception":"[object] (ErrorException(code: 0): Undefined variable: e at /var/www/html/stmd/app/Exceptions/Handler.php:76)
[stacktrace]
#0 /var/www/html/stmd/app/Exceptions/Handler.php(76): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError(8, 'Undefined varia...', '/var/www/html/s...', 76, Array)
#1 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(83): App\\Exceptions\\Handler->render(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Exceptions\\PostTooLargeException))
#2 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(55): Illuminate\\Routing\\Pipeline->handleException(Object(Illuminate\\Http\\Request), Object(Illuminate\\Http\\Exceptions\\PostTooLargeException))
#3 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(46): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#4 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#5 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#6 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#7 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(151): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#8 /var/www/html/stmd/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#9 /var/www/html/stmd/public/index.php(58): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#10 /var/www/html/stmd/index.php(4): include('/var/www/html/s...')
#11 {main}
"}
My Handler.php content is below:
public function render($request, Exception $exception)
{
if($this->isHttpException($exception)){
$logFile = 'laravel.log';
Log::useDailyFiles(storage_path().'/logs/'.$logFile);
//echo Route::getCurrentRoute()->getAction();
//echo $exception->getStatusCode();exit;
switch ($exception->getStatusCode()) {
case 404:
Log::info('Unable to find page.');
return response()->view('errors.404',[],404);
break;
case 500:
Log::error('In Server is really going wrong.');
return response()->view('errors.500',[],500);
break;
default:
return $this->renderHttpException($e);
break;
}
}
return parent::render($request, $exception);
}
}
Change
return $this->renderHttpException($e);
to
return $this->renderHttpException($exception);
in
app/Exceptions/Handler.php
You can handle the FileException exception inside your exception handler at app/Exceptions/Handler.php. Update the render method to add in the code you need. For example, if you'd like to return a validation exception, you will need to handle the validation inside the exception handler for the FileException exception.
public function render($request, Exception $exception)
{
if ($exception instanceof \Symfony\Component\HttpFoundation\File\Exception\FileException) {
// create a validator and validate to throw a new ValidationException
return Validator::make($request->all(), [
'your_file_input' => 'required|file|size:5000',
])->validate();
}
return parent::render($request, $exception);
}
This is untested, but should give you the general idea.
if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException)
return \Redirect::to('administrator/media')->with('errorMessage', 'Please upload an image.');
Related
I'm trying to catch errors that occur during HTTP client operations. If debugging is enabled APP_DEBUG=true then I get an error trace, if it is off, then it comes json response "message": "Server Error". But I need to catch exceptions, it doesn't work. Tried catch (\Illuminate\Http\Client\ConnectionException $e), but it didn't work. What am I doing wrong?
public function ExampleMethod()
{
try {
$response =
Http::withBasicAuth(env('REMOTE_LOGIN'), env('REMOTE_PASSWORD'))
->accept('application/json')
->retry(3, 2000)->timeout(12)
->withBody("dummy body content", "application/json")
->post($host . $url);
if ($response->ok()) {
//Do something
}
} catch (Exception $e) {
dd("CATCH IT");
}
}
There is an example from the documentation, the domain does not exist, and an exception handler should work somewhere, but it does not work
public function catchExceptins()
{
try {
$url = "domain-is-not-exist.com";
$response = Http::get($url);
if ($response->ok()) {
dd("200 OK");
}
//
if($response->failed()){
dd("FAILED");
}
//Below are the handlers that should work,
//but they do not respond when there is no domain
//or for example if the server response is 505
if($response->serverError()) {
dd("FAILED");
}
if($response->clientError()) {
dd("FAILED");
}
$response->throw(function($response, $e){
dd("FAILED");
})->json();
} catch (Exception $e) {
dd($e);
}
}
Laravel's HTTP client wrapper offers a mechanism for handling errors with a bunch of useful methods.
public function ExampleMethod()
{
try{
$response = Http::withBasicAuth(env('REMOTE_LOGIN'), env('REMOTE_PASSWORD'))
->accept('application/json')
->retry(3, 2000)->timeout(12)
->withBody("dummy body content", "application/json")
->post($host . $url);
//Check for any error 400 or 500 level status code
if($response->failed()){
// process the failure
}
//Check if response has error with 500 level status code
if($response->serverError()) {
//process on server error
}
//Check if response has error with 400 level status code
if($response->clientError()) {
//process on client error
}
// It also allows to throw exceptions on the $response
//If there's no error then the chain will continue and json() will be invoked
$response->throw(function($response, $e){
//do your thing
})->json();
}
catch(\Exception $e) {
//$e->getMessage() - will output "cURL error 6: Could not resolve host" in case of invalid domain
}
}
Laravel Docs - Http Client - Exception Handling
When you set APP_DEBUG=false, it just shows a generic error to the end user for security, but should give you the detailed error inside of the Laravel logs. 'All' APP_DEBUG=true does, is make the development process easier by displaying the log on the front end.
Your Laravel logs should be inside of "/storage/logs".
https://laravel.com/docs/9.x/configuration#debug-mode
https://laravel.com/docs/9.x/errors#configuration
I would like to figure out how to test that a widget throws an async exception.
Exception, that is created on the widget's initState:
Future<void> _asyncError() async =>
Future.delayed(Duration(microseconds: 1), () => throw FaultRoots.async);
The test, that does not detect the exception and then throws it:
try {
await tester.pumpWidget(widget);
await tester.pumpAndSettle();
expect(tester.takeException(), isNotNull);
expect(tester.takeException().toString(), contains(p.route));
} catch (ex) {
print(ex.toString());
}
Exception:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following message was thrown running a test:
/fault/async
When the exception was thrown, this was the stack:
#0 _FaultPageState._asyncError.<anonymous closure> (package:flutter_firebase_hello/pages/fault_page.dart:26:55)
#8 FakeTimer._fire (package:fake_async/fake_async.dart:316:16)
#9 FakeAsync._fireTimersWhile (package:fake_async/fake_async.dart:240:13)
#10 FakeAsync.elapse (package:fake_async/fake_async.dart:137:5)
#11 AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:965:28)
#14 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:72:41)
#15 AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:961:27)
#16 WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart:640:23)
<asynchronous suspension>
<asynchronous suspension>
(elided 10 frames from dart:async and package:stack_trace)
Async exceptions can be caught by runZonedGuarded:
await runZonedGuarded(() async {
await tester.pumpWidget(makeTestable(widget));
await tester.pumpAndSettle();
}, (error, stack) {
... error validation ...
});
My Flutter method that makes the http request. It even prints out the http url and invoking this same exact url on the browser returns status code 200 yet calling it programmatically using flutter's http.get returns error code 409.
Future<String> saveUser(String firstName, String lastName, String sex) async {
String url = domain +
'register?' +
'first_name=' +
firstName +
'&last_name=' +
lastName +
'&sex=' +
sex;
final response = await http.get(url);
print(url);
print(response.statusCode);
print(response.body);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
return response.body;
} else {
// If that response was not OK, throw an error.
return 'Failed to Register User';
}
}
This is flutter's console log. the number represents the error code, and the 'script' tags represent the response body
I/flutter (27919): http://filteredkenya.co.ke/baliach/register?first_name=Tyler&last_name=Mutai&sex=Male
I/flutter (27919): 409
I/flutter (27919): <script>document.cookie = "humans_21909=1"; document.location.reload(true)</script>
This is my Laravel's Controller method that's supposed to save data to DB and return a response (Has been mapped to both get and post methods):
public function register(Request $request)
{
$data = $request->all();
//Validation:
$validator = Validator::make($data, [
'first_name' => 'required|string|min:3',
'last_name' => 'required|string|min:3',
'sex' => 'required|string|min:3',
]);
//If there is an error in either one of the inputs
if ($validator->fails()) {
return response()->json($validator->errors());
}
$registration = new Registration;
$registration->first_name = $data['first_name'];
$registration->last_name = $data['last_name'];
$registration->sex = $data['sex'];
$registration->save();
return response()->json($data);
}
Turns out that my home wifi network is in some way resulting to an error 409 on the server. Testing the app on a different network yields correct results (Http Status Code 200). Why this happens, I'm not really sure.
I have solved the problem by changing the name of the url, if I had register.php I changed it to regis.php this made the variables refresh or something similar and it was solved.
I implement search functionalities with the help of solr via solarium in CodeIgniter.
I'm starting my website without solr connection (i.e. If the solr connection is stopped), My website throws the below warning message,
An uncaught Exception was encountered
Type: Solarium\Exception\HttpException
Message: Solr HTTP error: HTTP request failed, Failed to connect to localhost port 8983: Connection refused
Filename: C:\wamp\www\project-folder\project-name\vendor\solarium\solarium\src\Core\Client\Adapter\Curl.php
Line Number: 170
My doubt is if any chance to add exception handling in solr connection.
That means, If solr status is true it works as it is. If the solr status is false (Not in connection) the error warning is not displayed.
This above scenario is possible or not by using exception handling.
Update
My controller page,
function __construct()
{
parent::__construct();
$this->config->load('solarium');
$this->client = new Solarium\Client($this->config->item('solarium_endpoint'));
}
public function solrQuery()
{
$query = $this->client->createSelect();
$query->setStart(0)->setRows(1000);
// get the facetset component
$facetSet = $query->getFacetSet();
$facetSet->createFacetField('product_category_1')->setField('product_category_1');
$categories_data = $this->client->select($query);
}
Surround the relevant bits of code that throw exceptions in a try-catch block like so:
function __construct() {
parent::__construct();
$this->config->load('solarium');
try {
$this->client = new Solarium\Client($this->config->item('solarium_endpoint'));
} catch (\Exception $e) {
show_error($e->getMessage());
}
}
public function solrQuery() {
try {
$query = $this->client->createSelect();
$query->setStart(0)->setRows(1000);
// get the facetset component
$facetSet = $query->getFacetSet();
$facetSet->createFacetField('product_category_1')->setField('product_category_1');
$categories_data = $this->client->select($query);
} catch (\Exception $e) {
show_error($e->getMessage());
}
}
Of course you don't have yo use show_error() and can instead return false, or set your own headers and your own message.
i am trying to do axios.post method for sending the messages . But i am getting this error repeatedly.
my script looks like this
sendMsg(){
if(this.msgFrom){
axios.post('messages/sendMessage/',{
conID:this.conID,
msg:this.msgFrom
})
.then(response => {
console.log('saved successfully');
})
.catch(function (error) {
console.log(error.response);
});
}
}
Route looks like this
Route::post('/messages/sendMessage','Messages#sendmsg');
and controller looks like this
public function sendmsg(Request $request){
echo $request->msg;
}
and i am getting the error code 405,method not allowed , any solutions please.
I am going to make an assumption:
Your route is currently in the default api.php file
So you may need to modify your URL in the axios request to include the /api/:
/api/messages/sendMessage