totaljs / framework4

Total.js framework v4
https://www.totaljs.com
Other
97 stars 36 forks source link

An alternative to try/catch error handler #43

Closed LandyCuadra closed 2 years ago

LandyCuadra commented 2 years ago

Is the feature request related to a problem? Please describe.

I would like to stop using try/catch in schemas methods, so I would like to know if there is a way to create an error collector, that every error that happens in any method get handled by a single block of code

Describe the solution you'd like

`
try {

  //Operation

}catch(err){
  const {name, message} = err;
  $.invalid(name, message);
  console.error(`SCHM: ${schema.name} | $${workflow} | ${method} | ${err.stack}`);
}

`

I want to declare the catch handler only one time because it will always do the same

Describe alternatives you've considered

Tried overwritting the DEF.onError function, but could not find a way to send the controller to it

Additional context

petersirka commented 2 years ago

We don't use try/catch in the schemas. For example - here is a source code of one of our schema:

image

LandyCuadra commented 2 years ago

but it do not return anything to the user.

for example this code: Screenshot_20220114_122907

will broke because variable is not defined, so it throws an error to the console, but it do not return a error to the user. Screenshot_20220114_122834

like it would do with try/catch Screenshot_20220114_123257

and the time between the error and the 503 response is 6 second

LandyCuadra commented 2 years ago

What I would like to do is to send a controller to the default error handler to do a $.invalid() after showing the error in console or if there is a global way to return a response on error

petersirka commented 2 years ago

@LandyCuadra this is not possible, because ErrorBuilder can be created without controller - for example via EXEC() method.

molda commented 2 years ago

@LandyCuadra the example with the undefined variable is actualy a bug and not something you should need try/catch for. But if you want to avoid using try/catch you could try something like this:

// global try/catch wrapper
function trycatch(handler) {
    return async function($, value) {
        let result;
        let error;
        try {
            result = await handler($, value);
        } catch(e) {
            error = e;
        }

        if (!error)
            $.success(result);
        else
            $.invalid(); // or any other logic
    };
};

schema.setQuery(trycatch(async function($, value) {
    // do not use $.success or $.invalid here
    // just return data 
    return { anything: 'here' };
}));
petersirka commented 2 years ago

I'm closing issue.