Intellij: create a random number via IDE to use as error number / error code? - intellij-idea

see here: The proper way to do exception handling
say this code:
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided');
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found');
}
//..
}
i want to change that to:
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided', <SOMEVERYRANDOMNUMBER>);
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found', <SOMEVERYRANDOMNUMBER>);
}
//..
}
can intellij help me in selecting random numbers?

I personally use different types of Exception instead of exception code.
For example:
try{
...
} catch (PDOException e1){
// Show a message that we could not do SQL work
} catch (NumberFormatException e2){
// Show a message that input was not a valid number
} catch (Exception e){
// I'm not sure what was wrong but definitely there was some thing wrong
}
But if you still want random numbers, go to https://www.random.org, there are some number generators, copy values and define them as constants in your code (i guess that you are using PHP)

Related

How do I throw an exception and log as info?

Need a bit quick help with Kotlin. Here is the pseudocode: When there is a “specialCase” error, throw the exception and Log this exception as “Info”. This is the if statement I have. Does this look like a good approach?
if (error.contains (specialCase))
{
throw specialCaseDoesNotExistException
}
LOGGER.info("WriteSpecialCaseasInfoandNOTError")
Either you log before throwing or you could combine it into a single statement using also (reference):
if (error.contains (specialCase)) {
LOGGER.info("WriteSpecialCaseasInfoandNOTError")
throw specialCaseDoesNotExistException
}
if (error.contains (specialCase)) {
throw specialCaseDoesNotExistException.also {
LOGGER.info("WriteSpecialCaseasInfoandNOTError")
}
}

How do I catch a query exception in laravel to see if it fails?

All I'm trying to do is verify a query.
'SELECT * from table_that_does_not_exist'
Without that erroring out, I'd like to know it failed so I can return a response that states "Error: table does not exist" or the generic error.
The simplest way to catch any sql syntax or query errors is to catch an Illuminate\Database\QueryException after providing closure to your query:
try {
$results = \DB::connection("example")
->select(\DB::raw("SELECT * FROM unknown_table"))
->first();
// Closures include ->first(), ->get(), ->pluck(), etc.
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
// Note any method of class PDOException can be called on $ex.
}
If there are any errors, the program will die(var_dump(...)) whatever it needs to.
Note: For namespacing, you need to first \ if the class is not included as a use statement.
Also for reference:
Laravel 5.5 API - Query Exception
Laravel 8.x API - Query Exception
Wrap the lines of code you wish to catch an exception on using try-catch statements
try
{
//write your codes here
}
catch(Exception $e)
{
dd($e->getMessage());
}
Do not forget to include the Exception class at the top of your controller by saying
Use Exception;
If you want to catch all types of database exceptions you can catch it on laravel Exception Handler
if ($exception instanceof \PDOException) {
# render a custom error
}
for more details about how to use laravel Exception Handler check https://laravel.com/docs/7.x/errors
Laravel 8.x
try {
$model->save(); // Use Eloquent: https://laravel.com/docs/8.x/eloquent
} catch (\Throwable $e) {
return 'My error message';
}
Note* Need to specify \Throwable $e no Throwable $e.

How to tell the Session to throw the error query[NHibernate]?

I made a test class against the repository methods shown below:
public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File
{
try
{
_session.Save(FileToAdd);
_session.Flush();
}
catch (Exception e)
{
if (e.InnerException.Message.Contains("Violation of UNIQUE KEY"))
throw new ArgumentException("Unique Name must be unique");
else
throw e;
}
}
public void RemoveFile(File FileToRemove)
{
_session.Delete(FileToRemove);
_session.Flush();
}
And the test class:
try
{
Data.File crashFile = new Data.File();
crashFile.UniqueName = "NonUniqueFileNameTest";
crashFile.Extension = ".abc";
repo.AddFile(crashFile);
Assert.Fail();
}
catch (Exception e)
{
Assert.IsInstanceOfType(e, typeof(ArgumentException));
}
// Clean up the file
Data.File removeFile = repo.GetFiles().Where(f => f.UniqueName == "NonUniqueFileNameTest").FirstOrDefault();
repo.RemoveFile(removeFile);
The test fails. When I step in to trace the problem, I found out that when I do the _session.flush() right after _session.delete(), it throws the exception, and if I look at the sql it does, it is actually submitting a "INSERT INTO" statement, which is exactly the sql that cause UNIQUE CONSTRAINT error. I tried to encapsulate both in transaction but still same problem happens. Anyone know the reason?
Edit
The other stay the same, only added Evict as suggested
public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File
{
try
{
_session.Save(FileToAdd);
_session.Flush();
}
catch (Exception e)
{
_session.Evict(FileToAdd);
if (e.InnerException.Message.Contains("Violation of UNIQUE KEY"))
throw new ArgumentException("Unique Name must be unique");
else
throw e;
}
}
No difference to the result.
Call _session.Evict(FileToAdd) in the catch block. Although the save fails, FileToAdd is still a transient object in the session and NH will attempt to persist (insert) it the next time the session is flushed.
NHibernate Manual "Best practices" Chapter 22:
This is more of a necessary practice than a "best" practice. When
an exception occurs, roll back the ITransaction and close the ISession.
If you don't, NHibernate can't guarantee that in-memory state
accurately represents persistent state. As a special case of this,
do not use ISession.Load() to determine if an instance with the given
identifier exists on the database; use Get() or a query instead.

Force antlr3 to immediately exit when a rule fails

I've got a rule like this:
declaration returns [RuntimeObject obj]:
DECLARE label value { $obj = new RuntimeObject($label.text, $value.text); };
Unfortunately, it throws an exception in the RuntimeObject constructor because $label.text is null. Examining the debug output and some other things reveals that the match against "label" actually failed, but the Antlr runtime "helpfully" continues with the match for the purpose of giving a more helpful error message (http://www.antlr.org/blog/antlr3/error.handling.tml).
Okay, I can see how this would be useful for some situations, but how can I tell Antlr to stop doing that? The defaultErrorHandler=false option from v2 seems to be gone.
I don't know much about Antlr, so this may be way off base, but the section entitled "Error Handling" on this migration page looks helpful.
It suggests you can either use #rulecatch { } to disable error handling entirely, or override the mismatch() method of the BaseRecogniser with your own implementation that doesn't attempt to recover. From your problem description, the example on that page seems like it does exactly what you want.
You could also override the reportError(RecognitionException) method, to make it rethrow the exception instead of print it, like so:
#parser::members {
#Override
public void reportError(RecognitionException e) {
throw new RuntimeException(e);
}
}
However, I'm not sure you want this (or the solution by ire_and_curses), because you will only get one error per parse attempt, which you can then fix, just to find the next error. If you try to recover (ANTLR does it okay) you can get multiple errors in one try, and fix all of them.
You need to override the mismatch and recoverFromMismatchedSet methods to ensure an exception is thrown immediately (examples are for Java):
#members {
protected void mismatch(IntStream input, int ttype, BitSet follow) throws RecognitionException {
throw new MismatchedTokenException(ttype, input);
}
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
throw e;
}
}
then you need to change how the parser deals with those exceptions so they're not swallowed:
#rulecatch {
catch (RecognitionException e) {
throw e;
}
}
(The bodies of all the rule-matching methods in your parser will be enclosed in try blocks, with this as the catch block.)
For comparison, the default implementation of recoverFromMismatchedSet inherited from BaseRecognizer:
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
if (mismatchIsMissingToken(input, follow)) {
reportError(e);
return getMissingSymbol(input, e, Token.INVALID_TOKEN_TYPE, follow);
}
throw e;
}
and the default rulecatch:
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}

Closing indexreader

I've a line in my Lucene code:
try
{
searcher.GetIndexReader();
}
catch(Exception ex)
{
throw ex;
}
finally
{
if (searcher != null)
{
searcher.Close();
}
}
In my finally clause, when I execute searcher.Close(), will it also execute searcher.GetIndexReader().Close behind the scenes?
Or do I need to explicitly call searcher.GetIndexReader().Close() method to close IndexReader??
Thanks for reading.
Sorry, it's tough to understand what is the type of searcher in your snippet and how it was constructed. But you should not close the the index reader with searcher.GetIndexReader().Close(). The searcher.Close() will close all resources associated with it and index reader as well IF searcher IS NOT IndexSearcher instance constructed with IndexSearcher(IndexReader r). In that case you have to close index reader manually.
First of all, code like this is always a bad idea:
try {
// Do something
} catch(Exception ex) {
throw ex; // WRONG
}
You're just masking the source of the exception, and still throwing. Better just to delete those lines.
If you didn't create the IndexReader yourself, you don't need to close it yourself. Chances are high that you don't need to use the method getIndexReader at all.
Also, unless you're assigning to searcher within the try block, there's no need to check if it's null, since there's no way it could get a null value.
Here's an example of what your code should look like:
String myIndexDir = "/my/index/dir";
IndexSearcher searcher = new IndexSearcher(myIndexDir);
try {
// Do something with the searcher
} finally {
searcher.close();
}