How can I catch errors in middleware on nestjs - error-handling

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

Related

How to test a function in a catch block of try/catch?

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()
})

Nuxt.js - 'error not defined' when trying to throw 404 in failed await call within asyncData method

Starting to play with Nuxt.js this evening and mock blog data but having an issue with non existing data.
Heres my asyncData method when viewing a single blog post:
async asyncData({ params }) {
try {
const post = await axios.get(
`https://jsonplaceholder.typicode.com/posts/${params.id}`
)
return {
post: post.data
}
} catch (err) {
error({ statusCode: 404, message: 'Post not found' })
}
}
When visiting a valid ID and a 200 error is returned everything works as expected, but when the endpoint returns a 404 it tells me that 'error is undefined'
I could only find information on doing this error handling using a promise catch method as seen here: https://nuxtjs.org/guide/async-data/#handling-errors
How can I use the error method within the try catch error?
Thanks.
You have to inject the error object in your asyncData method to use it inside:
async asyncData({ error, params }) {
// your code
}

rxjs - handling async errors in finally

I'm interested in invoking an async function when I unsubscribe from an observable, however, I'm unable to handle the errors in a synchronized way once unsubscribing, for example I have the following piece of code, and the error isn't catched.
const observable = Observable.of(true).finally( async () => {
throw new Error('what');
});
try {
observable.subscribe().unsubscribe();
} catch (e) {
console.log('We did not capture this');
}
What are the possible ways of handling async errors in finally?
I think there're two problems:
Calling unsubscribe() won't do anything because of(true) sends next and complete notification immediately on subscription. So when you call unsubscribe() yourself you're already unsubscribed because of the complete notification. Then the actual call unsubscribe() won't do anything in this case.
When you mark a method as async it means you're in fact returning a Promise that is rejected. But .finally is expecting a function that it invokes and does nothing with it's return value. When you mark it as async it returns a Promise but nobody listens to it.
If you want to catch the error you will have to remove the async keyword,
const observable = Observable.of(true).finally(() => {
throw new Error('what');
});
with async it will turn it into an asynchronous function and won't be caught. What you are doing now is similar to
try {
setTimeout(()=> {throw new Error('what');},10)
} catch (e) {
console.log('We did not capture this');
}
Throw will excuted in the eventloop instead of the main thread.

Error handling in HAPI

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

How to catch PDO exception in Laravel 4.2?

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