Is it possible to retrieve the namespace of a raised error? - error-handling

When I raise an error from within an XQuery query, for instance with:
error( fn:QName( 'http://example.com', 'XMPL0001' ), 'Conflict' )
... the following is returned by BaseX (be it when communicating with the server, or from within the GUI)
Stopped at ., 1/7:
[XMPL0001] Conflict
Is it somehow possible to retrieve the namespace of the error (in this case http://example.com) as well?
I'm using a customized PHP client and I would like to use this information to prevent possible (future) conflicts with my custom error codes and parse the errors to throw either a standard BaseX\Exception or a custom SomeNamespace\Exception, depending on the namespace of the error.
I could, of course, simply use another error code pattern than the typical ABCD1234 XQuery pattern, to prevent possible (future) error code conflicts, but the possible use of a namespace appeals to me more, because I can then define an uniform Exception interface, such as:
interface ExceptionInterface
{
public function getCategory(); // the 4 alpha character part
public function getCode(); // the 4 digit part
}
I'm currently using BaseX 7.7.2, by the way.

Yes, you can retrieve information about the error using a few variables in the error namespace, which are in scope of the try-catch statement, like so:
declare namespace err = "http://www.w3.org/2005/xqt-errors";
try {
error( fn:QName( 'http://example.com', 'XMPL0001' ), 'Conflict' )
}
catch * {
namespace-uri-from-QName($err:code)
}
This assumes that you are using XQuery 3.0.

Related

Class not found - Laravel

Having issues with my Laravel application when I put it online. Locally, everything is working but now I'm having this error saying that the Class 'App\Models\Island' not found. I think I'm following the rules with letter sensitivity here, but I am not so sure what is the problem.
namespace App\Providers;
use App\Models\Status;
use App\Models\User;
use App\Models\Infrastructure;
use App\Models\Island;
use App\Models\Foreman;
use App\Models\Designer;
use App\Models\Engineer;
use App\Models\Type;
use Illuminate\Support\ServiceProvider;
use View;
Futher down the script, line 57 is also highlighted as part of the error message.
/**
* Infrastructure
*/
View::composer(['infrastructures.fields'], function ($view) {
$islandItems = Island::pluck('island_name','id')->toArray(); // line 57
$view->with('islandItems', $islandItems);
});

How to share a variable between two routers module in cro?

I try to use Cro to create a Rest API that will publish messages in rabbitMQ. I would like to split my routes in different modules and compose them with an "include". But I would like to be able to share the same connection to rabbitMQ in each of those modules too. I try with "our" but it does not work :
File 1:
unit module XXX::YYY;
use Cro::HTTP::Router;
use Cro::HTTP::Server;
use Cro::HTTP::Log::File;
use XXX::YYY::Route1;
use Net::AMQP;
our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;
my $application = route {
include <api v1 run> => run-routes;
}
...
File 2:
unit module XXX::YYY::Route1;
use UUID;
use Cro::HTTP::Router;
use JSON::Fast;
use Net::AMQP;
my $channel = $XXX::YYY::rabbitConnection.open-channel().result;
$channel.declare-queue("test_task", durable=> True );
sub run-routes() is export { ... }
Error message:
===SORRY!===
No such method 'open-channel' for invocant of type 'Any'
Thanks!
When you define your exportable route function you can specify arguments then in your composing module you can create the shared objects and pass them to the routes. For example in your router module :
sub run-routes ($rmq) is export{
route {
... $rmq is available in here
}
}
Then in your main router you can create your Queue and pass it in when including
my $rmq = # Insert queue creation code here
include product => run-routes( $rmq );
I've not tried this but I can't see any reason why it shouldn't work.
The answer by #Scimon is certainly correct, but it does not addresses the OP. On the other hand, the two comments by #ugexe and #raiph are spot-on, so I'll try to summarize them here and explain what's going on.
The error itself
This is the error:
Error message:
===SORRY!=== No such method 'open-channel' for invocant of type 'Any'
It indicates the invocant ($XXX::YYY::rabbitConnection) is of type Any, which is the type usually assigned to variables when they don't have a defined value; that is, basically, $XXX::YYY::rabbitConnection is not defined. It certainly is not since XXX::YYY is not included among the imported modules, as indicated by #ugexe.
The additioal problem indicated by the OP
That module was eliminated from the imported list because, as indicated by the OP
I certainly code it the wrong way because if i try to add use
XXX::YYY;, i get a Circular module loading detected error
But of course. since use XXX::YYY::Route1; which is file 2, is included in File 1.
The final solution is to reorganize files
That circular dependence probably points out to the fact that they should be in the same file, or else common code should be factored out to a third file, which would be eventually be included by both. So you should have something like
unit module XXX::YYY::Common;
use Net::AMQP;
our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;
And then
use XXX::YYY::Common;
in both modules.

Use antlr v4 for syntax check

Can I use antlr v4 for syntax check before I actually run the code?
Example :
I defined syntax: select * from table, I want to know the statement is correct or not before actually executing it.
Following is my code :
val listener = new SQLListener()
val loadLexer = new SQLLexer(new ANTLRInputStream(input))
val tokens = new CommonTokenStream(loadLexer)
val parser = new SQLParser(tokens)
val stat = parser.statement()
I tried but DefaultErrorStrategy won't throw an Exception
I tried this:
parser.addErrorListener(new BaseErrorListener {
override def syntaxError(recognizer: Recognizer[_, _ <: ATNSimulator],
offendingSymbol: scala.Any,
line: Int,
charPositionInLine: Int,
msg: String, e: RecognitionException ): Unit = {
println("==========2============"+msg)
throw new AssertionError("line: " + line + ", offset: " + charPositionInLine +
", symbol:" + offendingSymbol + " " + msg)
}
})
but get this:
Error: Note: the super classes of contain the following, non final members named syntaxError:
If the input contains any syntax errors, this will call the visitErrorNode method on the listener. So if you define that method in your listener, you'll see any errors that occur.
If your listener is directly executing the code (rather than first building an AST or other form of IR), you probably won't want your listener to even start executing when there's a syntax error. One way to achieve that would be to set the BailErrorStrategy instead of the DefaultErrorStrategy as the error handling strategy of your parser (using setErrorHandler on the parser). This will throw an exception as soon as a syntax error occurs.
If you don't want to abort on the first error and/or you want some additional checks beyond just syntax errors (like checking for certain types of semantic errors), an alternative is to have a listener just to perform those checks. Then you'd run your code-executing listener only if the error-checking listener does not find any errors.
You are on the right track here. Use your error listener to store the errors in a list while parsing. Afterwards you can then check that list.
That requires however not to do any action during the parsing process (e.g. in a parse listener) other than stuff related to the parsing process itself. Any follow up action (e.g. error markup in an editor) should be done after the parse run.
If you like to see an example of an application using this approach take a look at the parser module implementation of MySQL Workbench. It also demonstrates the 2-stage parsing strategy for quicker parsing.

Xtext: Customizing Error msg by unordered groups

I've defined an unordered group and it works like I expected. The only thing I would like to change is the error msg, which appears when an element of an unordered group isn't modelled yet. Is there an easy way to solve this? I tried already custom checks, but there I got an unexpected behaviour.
Following my rule for the unordered group and the error msg:
Element:
(name=ConfigurationName) &
(description=Description)? &
(tool=Tool) &
(model=Model) &
(interfaces=Interfaces)? &
(paramaters=Parameters)? &
(paramfile=ParamFile)?
;
rule ruleElement failed predicate: {getUnorderedGroupHelper().canLeave(grammarAccess.getElementAccess().getUnorderedGroup())}?
I want to change this error msg to something like: "The following elements are required in the configuration:...."
Xtext has a service called SyntaxErrorMessageProvider that is used to reword parser error messages. You have to define your messages on the parser level (so there will be no EMF model to use), but it is possible to get the original error message and the context, traverse it and provide your own error message.
To register this, open the «YourLanguage»RuntimeModule class, and add the following method:
public Class<? extends ISyntaxErrorMessageProvider> bindISyntaxErrorMessageProvider() {
return «YourLanguage»SyntaxErrorMessageProvider.class;
}
where «YourLanguage«SyntaxErrorMessageProvider is a class introduced by you, extending the class SyntaxErrorMessageProvider, where you can implement your custom function.
I works Automatic Validation customize,I create
public class MyDslLanguageSyntaxErrorMessageProvider extends SyntaxErrorMessageProvider {
}
And I Register it in the MyDslRuntimeModule:
public Class bindISyntaxErrorMessageProvider() {
return MyDslLanguageSyntaxErrorMessageProvider.class;}
But my problem is which package is used for this customization.I used org.xtext.example.mydsl.validation package for create java class .Also I do this customization with xtend class.I do not find enough source in the internet :(
You can use Java to write this Custom SyntaxErrorMessageProvider class, but to bind this you can bind in Runtime Module class. Also u can use any package to declare this class but declaring this class in same package where u have Runtime class makes sense

PHP error_log errors to MySQL

In a previous ticket i asked about logging PHP errors in MySQL which gives me:
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
// mysql connect etc here...
$sql = "INSERT INTO `error_log` SET
`number` = ".mysql_real_escape_string($errno).",
`string` = ".mysql_real_escape_string($errstr).",
`file` = ".mysql_real_escape_string($errfile).",
`line` = ".mysql_real_escape_string($errline);
mysql_query($sql);
// Don't execute PHP internal error handler
return true;
}
// set to the user defined error handler
$new_error_handler = set_error_handler("myErrorHandler");
I can make this work but only if it is triggerred like this:
trigger_error("message here");
However, I also want the error handler to be called for all errors such as syntax errors like:
echo "foo;
But these errors are just outputted to the screen, what am i doing wrong?
You can only handle runtime errors with a custom error handler. The echo "foo error in your example happens when parsing (i.e. reading in) the source. Since PHP can not fully parse the code, it can also not run your error handler on this error.
If You're forced to test if syntax is correct, You can use php_check_syntax function, with filename parameter PHP Manual php_check_syntax
php_check_syntax also provides second parameter, witch when used will be populated by the error string, as far as i remember
That's indeed terrible way of error logging
You don't need not a single advantage of a database. Would you make a database lookup for the certain line number? Or order your results by file name?
database is a subject of many errors itself.
You've been told already that it's impossible to catch a parse error at the program logic level, because a syntactically wrong program will never run.
Let's take your code as an example. It will raise a MySQL error (because of poorly formed query) which you will never see. As well as any other errors occurred. That's what I am talking about.