When I am catching a error and want to log it with the official swift logger swiftlog package like this:
do {
try something()
} catch {
logger.error(error.localizedDescription)
}
I get the message "Cannot conversation value of type 'String' to expected argument type 'Logger.Message'
I get a similar message for logger.error(error).
How to do this best?
Related
APIs:
https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY
https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY
API Call Method:
import 'package:http/http.dart';
import '../Models/fetched_data.dart';
Future<FetchedData?> fetchIndexDetails(String index) async {
final String url =
'https://www.nseindia.com/api/option-chain-indices?symbol=$index';
try {
final response = await get(
Uri.parse(url),
);
final FetchedData? fetchedData = fetchedDataFromJson(response.body);
return fetchedData;
} catch (e) {
print('$index Error: $e');
}
return null;
}
The json file is same for both the APIs, hence the model class too.
However, the second API call works smoothly but the first API call throws an error saying:
type 'double' is not a subtype of type 'int?'
Can anybody help me decode the problem here? Much tia :)
This is a JSON parsing issue for unmatched type parsing of the API and the your Dart Model ..
How to diagnose it?
You can always catch those errors while the development by enabling the dart debugger for uncaught exceptions, which gives you exactly the broken casting
type 'double' is not a subtype of type 'int?'
The API has returned a double value where an int is expected.
In your model or where appropriate replace the expected type to use num which int and double are both subtypes of
Check your model class where you have defined different variables and match with data type you are getting in response from the json.
There must be a variable you have defined in model class as int? but u r getting double as a response so u got to convert the data type .
Seems like you are trying to map a double to int?, the response had a double and you are assigning it to int?, add a breakpoint when mapping the response to see the corresponding field. You can try casting it to int or just changing the type all together.
If my single errors because of a networkexception return Single.just(false)
If my single errors because of another reason return Single.error
If my single succeeds return the original Single value.
this should be as easy as
getStudent(studentId)
.onErrorResumeNext { if (it is NetworkException) return #onErrorResumeNext Single.just(true)
return Single.error(it) }
Type inference failed. Expected type mismatch SingleSource found Single
Your Single needs to return the same type as your source (I'm assuming getStudent() isn't returning a Boolean). If you want to represent a "success" and "error" states, Kotlin has a Result class just for this.
E.g.
getStudent()
.map { student ->
// Your logic here may look different
Result.success(student)
}
.onErrorResumeNext { error ->
if (error is NetworkException){
Single.just(Result.failure(error))
} else {
Single.error(error)
}
}
This will catch network errors and wrap the exception in a Result, all other exceptions will be propagated downstream. You can then choose how to handle the error in your subscribe method.
Depending on your use case however, you may want to also look into using Maybe or the retry() operator.
I have a GoLang API with an SPA to consume it. What I do to errors in my API is return them until the handler where I test if an error from previous functions exist. If there is an error, I put it inside the response body, set status code to either 400 or 500 then return the response
in the handler function, to be able to create a clear message to the client side, I need to know what kind of error was returned, how do I do it?
I know about error types but I read about Dave Cheney's recommendation to just return an error along with a message (or wrap them in other words).
But if there are so many kinds of errors which might occur in the API call, then does it mean before returning the response, I need to check them all just to know what message I should return?
The first thing to say about errors is that just because there's an error interface
type error interface {
Error() string
}
Does not mean that the error returned from any given method can only have that method / information attached to it.
One common method is to define your own error interface:
type myError interface {
error // embeds the standard error interface
OtherMethod() string // can define own methods here
}
When writing methods and functions it's really important to return an error and not myError, else you couple that method to your error implementation and cause dependency nightmares for yourself later.
Now that we've decided we can return extra information from error, using our own error interfaces you've got 3 main choices.
Sentinel errors
Error Failure types
Errors with Behaviour
Sentinel errors
Sentinel errors are error values that are defined as package level variables, are exported and allow comparison to check for errors.
package myPackage
var ErrConnectionFailed = errors.New("connection failed")
func Connect() error {
// trimmed ...
return ErrConnectionFailed
}
A consumer of this example could use the connect function:
if err := myPackage.Connect(); err == myPackage.ErrConnectionFailed {
// handle connection failed state
}
You can do a comparison to check if the error returned is equal to the sentinel error of the package. The drawback is that any error created with errors.New("connection failed") will be equal, and not just the error from myPackage.
Error failure types
Slightly better than sentinel errors are error failure types.
We've already seen that you can define your own error interface, and if we say ours is now:
type MyError interface {
error
Failure() string
}
type Err struct {
failure string
}
func (e *Err) Error() string {
// implement standard error
}
func (e *Err) Failure() string {
return e.failure
}
const ConnFailed = "connection failed"
err := &Err{failure: ConnFailed}
In the consumer code you can get an error, check if it implements MyError and then do things with it.
err := myPackage.Connect()
if myErr, ok := err.(myPackage.MyError); ok {
// here you know err is a MyError
if myErr.Failure() == myPackage.ConnFailed {
// handle connection failed, could also use a switch instead of if
}
}
Now you have an idea of what caused the error which is nice. But do you really care what the cause was? Or do you only really care what you want to do to handle that error.
This is where errors with behaviour are nice.
Errors with behaviour
This is similar to defining your own error type, but instead you define methods that report information about that error. Given the example above, do you really care that the connection failed, or do you really only care if you can retry or if you need to error up the call stack again?
package myPackage
// this interface could report if the error
// is temporary and if you could retry it
type tempErr interface {
Temporary() bool
}
func (e *Err) Temporary() bool {
// return if the error is temporary or not
}
Now in the consumer (note you don't need to use the myPackage.tempErr), you can test using type assertions if the error is temporary and handle the retry case:
err := myPackage.Connect()
if tmp, ok := err.(interface { Temporary() bool }); ok && tmp.Temporary() {
// the error is temporary and you can retry the connection
}
To answer the question, it's very hard to say without the specifics of the service that you are trying to implement. But as broad advice, I would try and use the last of the 3 examples as much as possible.
If the consumer of your service sends you some input that's not valid:
err := doThing(...)
if inv, ok := err.(interface { Invalid() bool }); ok && inv.Invalid() {
// input is invalid, return 400 bad request status code etc.
}
If you want to return a specific message to a consumer, you could make that a method of your error type. Warning: this would give your packages knowledge that they are being used in a web service, etc.
err := doThing(...)
if msg, ok := err.(interface { ResponseMsg() string }); ok {
// write the message to the http response
io.WriteString(response, msg.ResponseMsg())
}
TL;DR you would need to handle all the cases, but you can create error types that make the code much easier to work with!
I created a drool file PersonTotalAccountsBalance.drl as below. I am beginner in the rules engine world.
package com.auhuman.rules;
import com.auhuman.Person;
import com.auhuman.Account;
function float getTotalBalance(Person person) {
float totalBalance = 0;
for (Account account : person.getAccounts()){
totalBalance += account.getBalance();
}
return totalBalance;
}
rule "PersonTotalAccountsBalance"
when
$node : Person(active == true)
then
float totalBalance = getTotalBalance($node)
modify($node) {
setTotalBalance(totalBalance);
}
end
Upon compile I am getting below error
Unable to compile the file: PersonTotalAccountsBalance.drl. Errors = [Unable to find #positional field 0 for class Person
: [Rule name='PersonTotalAccountsBalance']
]
Although this question is very old:
I had the same error message but I was working with decision tables in xls (excel) format. The table looked like this:
Note that $order:Order is in a merged cell goes across both the CONDITION and the ACTION columns. That cell is only allowed to be above CONDITION tables, not the ACTION tables. After unmerging I didn't get the error anymore:
I got a very similar error when defining the wrong values in the ACTION column for setting an attribute. When using values without quotes for a String attribute in the model Order I got the following error:
Unable to get KieModule, Errors Existed: Error Messages:
Message [id=1, kieBase=defaultKieBase, level=ERROR, path=status_rules/status.xls, line=21, column=0
text=Rule Compilation error The method setNextStatus(String) in the type Order is not applicable for the arguments (int)]
Message [id=2, kieBase=defaultKieBase, level=ERROR, path=status_rules/status.xls, line=5, column=0
text=Rule Compilation error The method setNextStatus(String) in the type Order is not applicable for the arguments (int)]
Message [id=3, kieBase=defaultKieBase, level=ERROR, path=status_rules/status.xls, line=13, column=0
text=Rule Compilation error The method setNextStatus(String) in the type Order is not applicable for the arguments (int)]
However in this case the error message was more precise.
I'm trying to catch my custom Error, but for some reason my catch statements where I name the error that I know is being thrown, it skips those, goes to the default catch, and then gives me a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) when I try to do print("Unexpected error \(error)")
Here's some abbreviated code:
This is the error that I have declared in my file that houses the class that I'm calling the method on (the class is called CC8DB):
public enum CC8RSVPError: Error {
case noEventOnDate
case invalidRSVPValue
}
I have a method declared as:
public func rsvpForEvent(_ inEventDate:Date?, forUserID inUserID:String, withValue inRSVPValue:String) throws -> CC8RSVPStatus
In another class were I'm calling this method, I have this:
do {
let rsvpResponse = try self.cc8DB.rsvpForEvent(inRSVPDate, forUserID: String(inMessage.author.id.rawValue), withValue: inRSVPValue);
...(other code to do when this doesn't fail)...
} catch CC8RSVPError.invalidRSVPValue {
...(Report specific error to user)...
} catch CC8RSVPError.noEventOnDate {
...(Report specific error to user)...
} catch {
...(Report general error to user)...
print("Error doing RSVP: \(error)");
}
And finally, in the CC8DB.rsvpForEvent() method, I'm triggering an error that does this:
throw CC8RSVPError.invalidRSVPValue;
The germane part of this method is:
public func rsvpForEvent(_ inEventDate:Date?, forUserID inUserID:String, withValue inRSVPValue:String) throws -> CC8RSVPStatus
{
var retStatus = CC8RSVPStatus(eventDate: nil, previousRSVP: "", newRSVP: "");
var upperRSVPValue:String = inRSVPValue.uppercased();
if (["YES", "MAYBE", "NO"].contains(upperRSVPValue)) {
//...(Code to do things when the info is correct)...
} else {
throw CC8RSVPError.invalidRSVPValue;
}
return retStatus;
}
For my test case where I'm seeing this, the inRSVPValue is "bla", to test what happens when a user doesn't enter a valid status value.
What I'm seeing is that rather than going into the catch that's specific for the CC8RSVPError.invalidRSVPValue case, it's going down to the general catch. In addition, I'm getting the EXC_BAD_INSTRUCTION on the line where I try and print the error value.
I've stepped through it to verify that I am indeed hitting the throw line that I think I am, and I can see in the debugger that the value of error is CC8DB.CC8RSVPError.invalidRSVPValue, but even if I try to do po error from the lldb command, I get the same exception error.
Has anyone seen this or know what I could have done to make do-try-catch not work right?
You could assign a constant named error inside your catch statement and inside the catch block read the constant and figure out what to do with it.
do something like:
} catch let error {
switch error {
case CC8RSVPError.noEventOnDate:
// code
case CC8RSVPError.invalidRSVPValue:
// code
}
}
Ok, I figured it out. I realized that somewhere along the way, some build setting got set so that I was statically linking into the binary (this is a command-line tool, a bot for Discord to be specific).
I saw some warnings about some of the Swift runtime libs being found in both the binary and the XCode developer runtime area, and realized that it might be that the error object was being used both in my CC8DB module in the binary and in the built-modules folder (or something to that effect).
I need to statically link for when I actually deploy the bot to where it's going to run, so I must have turned something on that won't turn off (I deleted the extra flags that I thought turned that on, but that wasn't fixing it).
Basically, I recreated my .xcodeproj file with swift package generate-xcodeproj to clear out whatever I broke, and now it works as expected.
Thanks to everyone who looked at this and offered help (especially #gmogames for his time and help). I'm sure it helped lead me down the path of figuring this out.