Scala's throw expects a Throwable, which js.Error is not.
I need to re-throw a JS error that was provided to me by a third party JS lib. Said lib will then catch that re-thrown error again and do something about it.
I could write a one-line npm module in JS: module.exports = function (e) { throw e; }, and add it to my npmDependencies, but I was wondering if there is a better solution for this.
You have to wrap the JS error in a js.JavaScriptException:
import scala.scalajs.js
throw js.JavaScriptException(e)
Related
I have following code
IAsyncOperation<bool> trythiswork()
{
bool contentFound{ false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result)
if (result)
{
contentFound = true;
}
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
When the result is false, it fails and throws but catch goes to fail fast and program terminates. How does log function terminate the program? Isn't it supposed to only log the exception? I assumed that I am handling this exception so program won't crash but it is crashing.
So how to throw and catch so that program does not terminate? I do want to throw. And also catch and preferably log the exception as well.
Thanks
The issue can be reproduced using the following code:
IAsyncOperation<bool> someAsyncFunc() { co_return false; }
IAsyncOperation<bool> trythiswork()
{
auto contentFound { false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result);
// throw std::bad_alloc {};
contentFound = true;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
int main()
{
init_apartment();
auto result = trythiswork().get();
}
As it turns out, everything works as advertised, even if not as intended. When running the code with a debugger attached you will see the following debug output:
The exception %s (0x [trythiswork]
Not very helpful, but it shows that logging itself works. This is followed up by something like
FailFast(1) tid(b230) 8007023E {Application Error}
causing the process to terminate. The WIL only recognizes exceptions of type std::exception, wil::ResultException, and Platform::Exception^. When it handles an unrecognized exception type it will terminate the process by default. This can be verified by commenting out the call to check_bool and instead throwing a standard exception (such as std::bad_alloc). This produces a program that will log exception details, but continue to execute.
The behavior can be customized by registering a callback for custom exception types, giving clients control over translating between custom exception types and HRESULT values. This is useful in cases where WIL needs to interoperate with external library code that uses its own exception types.
For C++/WinRT exception types (based on hresult_error) the WIL already provides error handling helpers that can be enabled (see Integrating with C++/WinRT). To opt into this all you need to do is to #include <wil/cppwinrt.h> before any C++/WinRT headers. When using precompiled headers that's where the #include directive should go.
With that change, the program now works as desired: It logs exception information for exceptions that originate from C++/WinRT, and continues to execute after the exception has been handled.
How to handle unahandled exceptions in blazor server razor component, In page model, I'm handling with try catch block, but some errors come from razor file and the circuit breaks, application stops. Kindly suggest me the solution to handle this.
I read alot about this issue and what I found that there is no way to make a global error handling right now for blazor, you can handle the error that related with http request like this:
if (!response.IsSuccessStatusCode)
{
var statusCode = response.StatusCode;
switch (statusCode)
{
case HttpStatusCode.NotFound: _navigation.NavigateTo("/Notfound", true);
break;
case HttpStatusCode.Unauthorized: _navigation.NavigateTo("/Error");
break;
default: _navigation.NavigateTo("/Error");
break;
}
throw new ApplicationException($"Reason: {response.ReasonPhrase}");
}
You need also to be carefull about using try catch inside blazor component with some proberty [inject] becuase maybe your blazor circuit will fail!.
You can read more about that in microsoft documents and correct if I am wrong.
I'm writing an app in Xamarin and was wondering if it's possible to externalize my strings I use in exceptions.
For example if I write in my code
throw new Exception("This is an error");
How can I externalize the errormessag "this is an error" ?
I already tried something like this :
throw new Exception("#string/errormessage")
and added errormessage to the Strings.xml file, but that didn't work.
Does anybody know if this can be done?
Assuming this is in your values\Strings.xml:
<string name="stackoverflow">StackOverflow Custom Exception String</string>
You can use it as your custom exception message via:
button.Click += delegate {
throw new Exception(this.Resources.GetString(Resource.String.stackoverflow));
};
With bluebird, let's say I want to catch an error and throw a different error.
DAO.getById('AccessTokens', token).then(function(matchingToken) {
return matchingToken;
}).catch(NotFoundError, function(err) {
Logging.error("caught a not found error"); // or some kind of logger...
throw err;
}).catch(function(err) {
throw ['DB Error - Tokens', err];
});
If I run this and a NotFoundError is thrown, I observe that the NotFoundError handler runs, then the generic error handler runs. I would like only the NotFoundError handler to run/propagate for a NotFoundError.
Is there a way to catch some errors and propagate them without also hitting the catchall error handler?
I could remove the catchall, but then it's possible for unknown errors to propagate. I could check for NotFoundErrors in the catchall, but that seems like duplicated behavior.. is there another option?
No, but let's talk about why
Currently - no, it was considered in the past but the use case was not convincing enough at the moment. Petka Gorgi and I discussed it in IRC at a point and generally agreed that using .catch(function(){ (a catch all) is not the greatest idea - not knowing what might fail is problematic and typically if you fail for a reason you don't know - you want to restart the server since it is unclear how you'd recover.
Personally, I'd just remove the catch-all - especially since it throws something that is not an error (so no stack trace, which is problematic and deteriorating in terms of debugging anyway). You can log errors globally and shut down gracefully.
I'm an adult and you're not the boss of me
Fine, you're right. The library is opinionated towards what I think are good error handling practices. Your opinion may vary and you can write a catch-all in the way you'd like. Sadly, I've been coding Haskell all day, so this might seem a little functional in style - you can always just catch types in the catch-all:
function typeT(type){
return function(item){ return item instanceof type; };
}
function not(fn){
return function(){ return !(fn.apply(this, arguments); };
}
DAO.getById('AccessTokens', token).then(function(matchingToken) {
return matchingToken;
}).catch(NotFoundError, function(err) {
Logging.error("caught a not found error"); // or some kind of logger...
throw err;
}).catch(not(typeT(NotFoundError)), function(err) { // predicate function catch clause
throw ['DB Error - Tokens', err];
});
At compile (macro) time, calling
Context.parse("a bad expression", somePos)
produces an error that cannot be caught in a try-catch block (Edit: this is wrong, see below). Is there a way to catch this error? Context.parseInlineString() doesn't seem to work either.
Others functions such as Context.typeExpr() have a similar problem.
Edit:
The type of catch was wrong. I did:
try {...}
catch (err:String) {...}
What you have to do:
try {...}
catch (err:Dynamic) {...}
Careful reading of the documentation explains this. This is different than Java for which there is one type of exception per error. In Haxe, most errors are strings, but there are some others like the one here.
The following works for me:
import haxe.macro.*;
class Test {
macro static function test() {
try {
Context.parse("a bad expression", Context.currentPos());
} catch(e:Dynamic) {
trace(e); //Test.hx:8: Missing ;
}
return macro {};
}
static function main() {
test();
}
}