Use custom error classes with constrained types in Pydantic - pydantic

The documentation specifies that: you can also define your own error classes, which can specify a custom error code, message template, and context.
In the example from the link above, a validator is defined to validate an attribute and the custom error NotABarError is raised from the validation method, which then raises a Pydantic ValidationError.
Similarly, is there a way to raise custom exceptions with constrained types? The message could be the same as the default one from pydantic.error_wrappers.ValidationError, but raised from a custom error class, rather than the Pydantic's ValidationError?

Related

What are all the different error types in Rust?

I'm learning Rust and can't find a list of all error types. When a function is returning a Result, does the standard library have a group of predefined errors available for use?
I know custom error types can be made in Rust, is that the solution? Make all custom errors types?
It's not well defined what "an error type" would mean, so no, there is no global list of errors.
If you mean "is there a list of all the types that are used as Result::Err, the answer is still no. There are methods like slice::binary_search which return Result<usize, usize>. Is usize to be considered an error type? What if a Result::Err is constructed entirely inside of a function and never leaves it; is that type considered an error type? What about a generic type that contains a Result<i32, E>; should any concrete E be called an error type?
If you mean "is there a list of all the types that implement std::error::Error, then the answer is "kind of". See How can I get a list of structs that implement a particular trait in Rust? for details.
does the standard library have a group of predefined errors
Yes.
available for use
Sometimes. io::Error allows you to construct your own error value, but num::ParseIntError does not.
is that the solution? Make all custom errors types?
Generally, yes.
See also:
How do you define custom `Error` types in Rust?
Result types are often aliased in the standard library. If you see a function in the standard library documentation, you can click on Result, which should lead you to the aliased type (e.g. std::io::Result)
You can then see which kind of Error is used in the Result.
The documentation also has a list of all enums and structs in the standard library that implement the Error trait.
a list, although not complete, can be found at
https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/std/error/trait.Error.html

Is there an efficient way to avoid instantiating a class with syntax errors?

As you may know, it is pretty easy to have active code of a class containing syntax errors (someone activated the code ignoring syntax warnings or someone changed the signature of a method the class calls, for instance).
This means that also dynamic instantiation of such a class via
CREATE OBJECT my_object TYPE (class_name).
will fail with an apparently uncatchable SYNTAX_ERROR exception. The goal is to write code that does not terminate when this occurs.
Known solutions:
Wrap the CREATE OBJECT statement inside an RFC function module, call the module with destination NONE, then catch the (classic) exception SYSTEM_FAILURE from the RFC call. If the RFC succeeds, actually create the object (you can't pass the created object out of the RFC because RFC function modules can't pass references, and objects cannot be passed other than by reference as far as I know).
This solution is not only inelegant, but impacts performance rather harshly since an entirely new LUW is spawned by the RFC call. Additionally, you're not actually preventing the SYNTAX_ERROR dump, just letting it dump in a thread you don't care about. It will still, annoyingly, show up in ST22.
Before attempting to instantiate the class, call
cl_abap_typedescr=>describe_by_name( class_name )
and catch the class-based exception CX_SY_RTTI_SYNTAX_ERROR it throws when the code it attempts to describe has syntax errors.
This performs much better than the RFC variant, but still seems to add unnecessary overhead - usually, I don't want the type information that describe_by_name returns, I'm solely calling it to get a catchable exception, and when it succeeds, its result is thrown away.
Is there a way to prevent the SYNTAX_ERROR dump without adding such overhead?
Most efficient way we could come up with:
METHODS has_correct_syntax
IMPORTING
class_name TYPE seoclsname
RETURNING
VALUE(result) TYPE abap_bool.
METHOD has_correct_syntax.
DATA(include_name) = cl_oo_classname_service=>get_cs_name( class_name ).
READ REPORT include_name INTO DATA(source_code).
SYNTAX-CHECK FOR source_code MESSAGE DATA(message) LINE DATA(line) WORD DATA(word).
result = xsdbool( sy-subrc = 0 ).
ENDMETHOD.
Still a lot of overhead for loading the program and syntax-checking it. However, at least none additional for compiling descriptors you are not interested in.
We investigated when we produced a dependency manager that wires classes together upon startup and should exclude syntactically wrong candidates.
CS includes don't always exist, so get_cs_name might come back empty. Seems to depend on the NetWeaver version and the editor the developer used.
If you are certain that the syntax errors are caused by the classes’ own code, you might want to consider buffering the results of the syntax checks and only revalidate when the class changed after it was last checked. This does not work if you expect syntax errors to be caused by something outside those classes.

Morphia Gives "Possible Heterogeneous Collection" Warning For Non-Collection Field

This is a follow-up question to Manual Conversion of 3rd Party Class With Morphia
I've an #Entity class which has a field of type javax.activation.MimeType. When I run my application I see a warning message in the output window, telling
WARNING: The multi-valued field
'javax.activation.MimeTypeParameterList.parameters' is a possible
heterogeneous collection. It cannot be verified. Please declare a
valid type to get rid of this warning. class java.lang.Object
I've already written and registered a type converter class for the type "MimeType", which effectively just ignores its 'parameters' field. But the warning keeps coming.I debugged it and saw that the warning was issued when datastore.ensureIndexes(); is called.
I tried writing a type converter for "MimeTypeParameterList" type but it didn't supress the warning. I can't just go and put a #Transient annotation over the field declaration because it's third party code (Java SE core!), not mine.
Is there an "elegant" way to eliminate this warning?
I just pushed a change to morphia's github repo that suppresses that logging for you. It'll be in 0.108 or you can build it locally if you want to try it out.

Mule DataMapper MEL custom functions or calling custom transformer

I have a question relating to the DataMapper component and extending the behaviour. I have a scenario where I'm converting one payload to another using the DataMapper. Some of the elements in my source request as strings (i.e. Male, Female) and these values need to be mapped to ID elements, known as enums in the target system. A DBLookup will suffice but because of the structure of enums (a.k.a lookup tables) in the target system I'd need to define multiple DBLookups for the values which need to be changed. So I'm looking to develop a more generic way of performing the mapping. I've two proposals, which I'm currently exploring
1) Use the invokeTransformer default function in to call a custom transformer. i.e.
output.gender = invokeTransformer("EnumTransformer",input.gender);
However, even though my transformer is defined in my flow
<custom-transformer name="EnumTransformer" class="com.abc.mule.EnumTransformer" />
Running a Preview in the DataMapper fails with the following error (in Studio Error Log)
Caused by: java.lang.IllegalArgumentException: Invalid transformer name 'EnumTransformer'
at com.mulesoft.datamapper.transform.function.InvokeTransformerFunction.call(InvokeTransformerFunction.java:35)
at org.mule.el.mvel.MVELFunctionAdaptor.call(MVELFunctionAdaptor.java:38)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getMethod(ReflectiveAccessorOptimizer.java:1011)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getMethod(ReflectiveAccessorOptimizer.java:987)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:377)
... 18 more
As the transformer is scoped to my flow and the datamapper is outside this scope do I assume it is now possible to invoke a custom transformer in a datamapper? Or do I require additional setup.
2) The alternative approach would be to use "global function". I've found he documentation in this area to be quiet weak. The functionality is referenced in the the cheat sheet and there is a [jira](
https://www.mulesoft.org/jira/browse/MULE-6438) to improve the documentation.
Again perhaps this functionality suffers from a scope issue. Questions on this approach is if anyone can provide a HOWTO on calling some JAVA code via MEL from a data mapper script? This blog suggests data mapper MEL can call JAVA but limits it's example to string functions. Is there any example of calling a custom JAVA class / static method?
In general I'm questioning if I am approaching this wrong? Should I use a Flow Ref and call a JAVA component?
Update
It is perfectly acceptable to use a custom transformer from the data mapper component. The issue I was encountering was a Mule Studio issue. Preview of a data mapping which contains a transformer does not work because the mule registry is not populated on the mule context as mule is not running.
In terms of the general approach now that I have realized the DB Lookup can accept multiple input parameters I can use this to address my mapping scenario.
Thanks
Rich
Try by providing complete class name

What type of IEnumerable should INotifyDataErrorInfo.GetErrors return?

It blows my mind that the official document at MSDN doesn't say anything about what the underlying object type of the enumerable that returned by GetErrors of INotifyDataErrorInfo should be: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo.geterrors(v=vs.95).aspx
Options are: System.String, System.Object, MyCustomObject, ISomeOtherShitThatDoesntHaveAnythingToDoWithValidationWhatsoever
Can anybody explain to me how an arbitrary enumerable of object can be OK for notifying about errors without making any assumptions about its structure?
The docs for INotifyDataErrorInfo give more information:
The validation errors returned by the GetErrors method can be of any type. However, if you implement a custom error type, be sure to override the ToString method to return an error message. Silverlight uses this string in its default error reporting.
Custom error objects are useful when you provide custom error reporting in the user interface. For example, you can create a template for the reporting ToolTip that binds to an ErrorLevel property in order to display warnings in yellow and critical errors in red.
There's a link in the Examples section of GetErrors back to that documentation:
For an example of an implementation of this method, see the INotifyDataErrorInfo class overview.
I agree it's less clear than it might be, but the documentation is there...