Can anyone help me on how to catch PDO exceptions in Laravel 4.2? I can catch the Fatal or Runtime exceptions using App::error and App::fatal in /app/start/global.php, but can't catch the PDO exception in any way. I don't want to tamper the Laravel base classes. I tried registering global exception handler but that didn't worked as well. Currently I've the following code in my global.php
App::error(function(Exception $exception, $code)
{
Log::error($exception);
return Response::view("errors.{$code}", array(), $code);
});
App::error(function(RuntimeException $exception)
{
Log::error($exception);
return Response::view("errors.500", array(), 500);
});
App::fatal(function($exception)
{
header("HTTP/1.1 500 Internal Server Error");
echo '<center><h3>Sorry! Something is wrong with this request!</h3></center>';
exit;
});
App::error(function(InvalidUserException $exception)
{
Log::error($exception);
return Response::view('errors.401', array(), 401);
});
How to add the PDOException block here or anywhere required?
Thanks in advance.
I guess that simply passing PDOException to your closure will catch the error like:
App::error(function(\PDOException $exception)
{
Log::error($exception);
return Response::view('errors.401', array(), 401);
});
Related
I am trying to catch errors with try-catch structure in middleware. I call next function in try block and if I have an error like null reference etc., I wait to catch the error in catch block. But it is not working.
export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
try {
next();
} catch (error) {
console.log(error);
}
}
According to the documentation, catching all unhandled exceptions can be done using an exception filter.
You can learn more about how to use a global exception filter on the documentation as there is a section about it: https://docs.nestjs.com/exception-filters#catch-everything
I have a custom package that is called if an error is thrown in the catch block of a try/catch. I want to test that the logFunction.error function is called. How do I test this function in the catch block? I'm passing in a mock jwt. I'm using jwtDcode (https://www.npmjs.com/package/jwt-decode) to decode my jwt. If it fails, an error is thrown the logFunction.error() returns a details object. Is this the correct way to set up this unit test?
file.js
jwtFunction ({commit}, idToken) {
try {
jwtDecode(idToken)
// do some logic
}catch (error) {
logFunction.error({
details: {
event: 'invalid jwt'
message: `${error.message} of ${idToken}`
timeStamp: Date.now()
}
})
commit(types.setApplicationError, error)
}
file.spec.js
it('[positive] should commit application error if jwt fails to decode', () => {
const mockIdToken = {}
const spy = jest.spyOn(logFunction, 'error')
actions.jwtFunction({ commit }, mockIdToken)
expect(spy).toHaveBeenCalled()
})
Catch all and any errors in a hapi request lifecycle.
I have a signup handler,
public signup(request: Hapi.Request, reply: Hapi.Base_Reply) {
this.database.user.create(request.payload).then((user: any) => {
return reply({
"success": true
});
}).catch((err) => {
reply(Boom.conflict('User with the given details already exists'));
});
}
Now, I am catching the error, but I can't be always sure that I will get this error message only. What if there is an error in the database?
How to catch such database errors or any other unknown errors for all the requests. ???
Maybe you have to return the err.message in your reply like
reply(Boom.conflig(err.message))
or if you want to manage or manipulate the error you have to verify the type of error like
if (err instanceof DatabaseError) {
// manage database error
}
I figured out a way to handle such errors in Hapi.
What I was looking for was a PreResponse handler. Now, the PreResponse handler can log all the errors and I can throw a 500 error response.
What I am saying is by simply writing
reply(err)
I can send a 500 error and can catch this error using preResponse handler. Something like this,
server.ext('onPreResponse', (request: Hapi.Request, reply: Hapi.ReplyWithContinue) => {
const response = request.response;
if (!response.isBoom) { // if not error then continue :)
return reply.continue();
}
console.log(response);
return reply(response);
});
This is what I have.. but I doubt that this is any legit.
Basically what am I trying to achieve is that Im fetching an item and if it fails, I wanna to make a post request.
try {
const response = yield call(axios.get, `/api/cars/${action.payload.car}`)
yield put({type: RECEIVE_CAR, requestPending : false, data: response.data})
} catch (e) {
console.log(e)
try {
const response = yield call(axios.post, `/api/cars/`, action.payload)
yield put({type: RECEIVE_CAR, requestPending : false, data: response.data})
} catch (error) {
console.log(error)
}
}
This is normal practice in Javascript development. It is suggested in the Javascript reference here
You could also write another saga for failure and instead invoke that saga in the catch statement.
When I create request to the server:
<script language="javascript" type="text/javascript">
function ajaxFunction()
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.write(ajaxRequest.responseText);
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "http://www.bbc.co.uk", true);
ajaxRequest.send(null);
}
</script>
Why response is nothing? Why response isnt html code of this web site?
This should work (I don't have time to test it right now.)
function ajaxFunction() { //Added open {
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Removed additional try / catch
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.write(ajaxRequest.responseText);
document.myForm.time.value = ajaxRequest.responseText;
}
}; // Added semi-colon to the end of the anonymous function definition
ajaxRequest.open("GET", "http://www.bbc.co.uk", true);
ajaxRequest.send(null);
}
A few notes:
White space is not required for the most part in Javascript, but proper indentation makes it much easier to spot syntax errors.
When you bind an attribute to an anonymous function you need to follow your } with a ;
Once you understand how this works, dig into one of the larger libraries ajax functions / modules. (Learning is always a good thing, and ajax is one of those areas that really needs a few dozen man-hours of work to encounter all the differences between browsers.)+
ADDENDUM:
Cross-domain ajax requests are very difficult to do right (i.e. safely, securely, and without throwing errors) -- they are forbidden to javascript directly by the Same-Domain Origin policy.
See this question and this one for more discussion on the subject and ways to get around it with a proxy or with jsonp
+ jQuery's ajax function is 325 lines long (and that's not counting $.ajax.settings or $.extend())
You might consider using a library like jQuery to do AJAX requests - they handle all the cross-browser quirks for you, and do a lot of extra work to boot. Your code could be as simple as
$.get(
'http://www.bbc.co.uk',
function(data) {
// do something with data
}
);`