Should i print error message in logs or inside exception or both? - error-handling

I have this code in Scala:
logger.error("Repository does not exists or does not contains 'definitions' directory")
throw new FileNotFoundException("Repository does not exists or does not contains 'definitions' directory")
Should i write message twice? Or should i only log the error and throw empty exception?

It depends, use cases to use cases.
If your log statement is within dev-scope then there is no need to throw exception to the source/caller. you can log exception and silent it and return back useful message/code to source/caller.

Related

How would I print out errors?

In the software called Roblox studio I need help making a script that whenever an error happens in game, it would print out the error again using the normal print function something like this example here:
Local error = —-whatever the error that happened was
Print(error) —- so it just simply prints it back out
Roblox provides a few different ways to keep track of when errors are thrown in your Scripts and LocalScripts.
If you want to observe errors locally in a script, and you know a specific chunk of code may throw errors, you can use pcall() as a try-catch block.
local success, result = pcall(function()
error("this is a test error message")
end)
if not success then
print("An error was thrown!")
print(result) --"this is a test error message"
end
If you want to observe errors across all of your scripts, you can attach a callback to the ScriptContext.Error signal. This signal fires any time any error is thrown. It provides information about the error, including the message, the callstack, and a reference to the script that threw the error.
Warning : ScriptContext.Error only fires in the context of the script that registers it. A Script will only observe errors thrown in server scripts, and registering in a LocalScript will only observe errors thrown on the client.
local ScriptContext = game:GetService("ScriptContext")
ScriptContext.Error:Connect( function(message, stack, context)
print("An error was thrown!")
print("Message : ", message)
print("Stack : ", stack)
print("Context :", context:GetFullName())
end)
Similarly, if you only care about the error messages themselves, you can also observe them being printed out to the Output window using the LogService.MessageOut signal. This signal fires any time anything is logged to Output. This includes messages, warnings, and errors.
local LogService = game:GetService("LogService")
LogService.MessageOut:Connect( function(message, messageType)
if messageType == Enum.MessageType.MessageError then
print("An error was thrown!")
print(message)
end
end)
Use the stderr stream from io library to print debug messages.
-- Define debug function based in print
function debug(...) io.stderr:write(table.concat({...}, '\9') .. '\n') end
-- Debug acts as a regular "print()", but it writes to stderr instead
debug('[filename.lua]', 'debug')
Use "error()" function to print errors.
if true then
error("It should not be true!")
end
If you want to catch errors from a function, use xpcall()
-- Define debug
function debug(...) io.stderr:write(table.concat({...}, '\9') .. '\n') end
xpcall(
function()
local b = {}
-- This will throw an error because you cant index nil values
print(a.b)
end,
function(err)
debug('[xpcall]', err)
end
)
xpcall() wont stop the execution in case of error, so you only need to encapsulate your code in it if you want to catch any unexpected errors at runtime.

Spring RestController response mixed with PrometheusMeterRegistry error message

Env: Springboot-2.0.7.RELEASE (embedded tomcat-8.5.35), JDK-1.8.0_181, micrometer-registry-prometheus-1.0.8
Desc: using #Timed on controller method and WebMvcMetricsFilter with custom WebMvcTagsProvider.
Demo project: https://github.com/kenix/resp-mix
If PrometheusMeterRegistry already created a meter with a set of tags, it won't create another meter with same name and a set of different tags. It throws IllegalArgumentException with the aforementioned reason. This happens after the normal processing of request, which is successful (response now has the converted JSON). The exception isn't caught in spring's WebMvcMetricsFilter (i.e. catch the exception in its catch-clause. BTW, ControllerAdvice doesn't help), but is caught by tomcat's StandardHostValve, which renders his own error message (it cannot know where this exception is from) into response too. This leads to an illegal JSON as the rendered result.
Question 1: should WebMvcMetricsFilter catch and handle this Exception thrown by PrometheusMeterRegistry and not throw it further up?
Question 2: have seen that exception in filter chain before hitting the actual processing is handled as expected. What about exception after a successful actual processing? Any references?
To trigger this case:
curl -i localhost:8080/hi/foo/there
curl -i localhost:8080/hi/blah/there
Question 1: No, WebMvcTagsProvider handles HTTP Exceptions.
Question 2: Try using ControllerAdvice and catch the IllegalArgumentException there.

F#: UnitTest case failled

Consider i have a function like newConvert. I am sopposed to recieve an error for newCovertor("IL") . To generate this erorr: I used failwith "Invalid Input"
The erorr is :
System.Exception: Invalid Input
> at FSI_0160.inputChecker(FSharpList`1 numberList) in C:\Users\Salman\Desktop\coursework6input\itt8060-master\coursework6input\BrokenRomanNumbers\Library1.fs:line 140
at FSI_0160.newCovertor(String romanNumber) in C:\Users\Salman\Desktop\coursework6input\itt8060-master\coursework6input\BrokenRomanNumbers\Library1.fs:line 147
at <StartupCode$FSI_0165>.$FSI_0165.main#() in C:\Users\Salman\Desktop\coursework6input\itt8060-master\coursework6input\BrokenRomanNumbers\newtest.fs:line 32
Stopped due to error
I used FsUnit and Nunit, they are loaded and installed and working rightly.
Then I made a tes for it using
[<TestFixture>]
type ``Given a Roman number15 ``()=
[<Test>]
member this.
``Whether the right convert for this number must be exist``()=
newCovertor("IL") |> should equal System.Exception
I cannot understand!! The function fails rightly, but the test does not accept it, so why??????
newCovertor does not produce a System.Execption - it throws it - so you never get to the should equal ... part
to catch the exception with FsUnit you have to wrap it as an action:
(fun () -> newCovertor("IL") |> ignore) |> should throw typeof<System.Exception>
also see the really good docs - there are quite a few ways to achieve this
The reason your version is not working is that NUnit will normaly mark a test as failed exactly when a exception is thrown inside the test-methods body - which you do.
If you wrap it in an action than the should throw can choose to execute this delayed action inside try ... match block to catch the expected exception and filter it out (or in this case throw an exception if there where none)
btw: just like in C#/VB.net you can also use the ExpectedExceptionAttribute from NUnit on the method level if you like - this way the test-framework will handle it for you.

Writing Codeception CLI test; want to throw exception but not have it fail the test

I forked Codeception/Codeception and added a Command module check that throws an exception.
When testing, this exception causes the test to fail but I'm running a test to force the exception and failure, to make sure it catches it.
Here's the edit to src/Codeception/Command/GenerateSuite.php
if ($this->containsInvalidCharacters ($suite)) {
throw new \Exception("Suite name '{$suite}' contains invalid characters. ([A-Za-z0-9_]).");
}
When updating tests/cli/GenerateSuiteCept.php when I run the command $I->executeCommand('generate:suite invalid-suite'); it fails because I'm throwing the exception in src/Codeception/Command/GenerateSuite.php in the first place.
Here is the addition to tests/cli/GenerateSuiteCept.php:
$I->executeCommand('generate:suite invalid-dash-suite');
When I run it, it says it failed. However, I want it to pass because I'm deliberately adding the dash to verify it catches invalid characters. What is the best way to do that? I'm wary of a try/catch block in these tests. I'm not sure if that is the best way to do that.
After looking at the other Codeception tests, I found this to be a better way than throwing an exception:
if ($this->containsInvalidCharacters ($suite)) {
$output->writeln("<error>Suite name '{$suite}' contains invalid characters. ([A-Za-z0-9_]).</error>");
return;
}
So I modified the test to:
$I->expect ('suite is not created due to dashes');
$I->executeCommand('generate:suite invalid-dash-suite');
$I->seeInShellOutput('contains invalid characters');

When to use `save` vs `save!` in model?

According to save bang your head, active record will drive you mad, we should avoid using save! and rescue idiom for exceptional situations. Given that, say a model needs to #post.mark_rejected.
If the code in mark_rejected fails due to one of the below problems, should an exception be thrown? :
if there is a validation problem
if a non-nullable-field was being assigned a null
if there was a connection loss to database
If we do not throw an exception, then:
controller action would have to check for return value of mark_rejected and do it's thing
we are not expecting an exception from that method call, so we do not write a rescue clause in the controller action, thus the exception bubbles up to (..wherever..) and will probably show up as some (500 HTTP?) error
Example code:
def mark_rejected
...
save!
end
or
def mark_rejected
...
save
end
save! will raise an error if not successful.
save will return boolean value like true or false.
There's more overhead in an exception, so there is a performance issue, especially when it can be expected that it will likely be thrown often, as is the case with save.
It is fewer lines of code to check if the return value is false than rescue an exception, so I don't see how it's a problem having to check for the return value if you already have to rescue the exception. How often would an exception thrown by save! ever have to bubble-up the call stack in practice? Rarely, if ever, in my experience.
If there is an exception thrown when calling save as opposed to save! you should want it to show a 500 error page because that's what happened: an unrecoverable, unknown, unexpected internal server error.
Suggestion: use save when it's on the last line; save! otherwise.
The idea: if the method is returning the save's result you should not throw exception and let the caller to handle save problems, but if the save is buried inside model method logic you would want to abort the process with an exception in case of failure.