org.rythmengine.exception.CompileException: Unhandled exception type Exception - rythm

When trying out the rythm template code below via the Rythm engine fiddle at http://fiddle.rythmengine.com/#/editor
I get the error:
org.rythmengine.exception.CompileException: Unhandled exception type Exception
the template I tried is:
#{
class Field {
String description;
String getDescription() throws Exception {
return description;
}
}
Field field=new Field();
field.description="test";
}
the field description is: #(field.getDescription())
I have looked thru the documentation for some kind of try/catch construct and consulted my favorite search engine. I didn't find a hint on how to handle exceptions.
How are exceptions to be handled in Rythm template code?

You need to make sure you do NOT throw out checked exception. Change your code to :
#{
class Field {
String description;
String getDescription() throws RuntimeException {
return description;
}
}
Field field=new Field();
field.description="test";
}
the field description is: #(field.getDescription())
And it should work

Related

JSON parse error: Unrecognized field MongoDB Spring Boot

I am trying to save the following Java object as a document in MongoDB, here are my classes:
public class GenericIpConfig {
String connection_type;
String port;
String port_ingenico;
String ip;
String ip_ingenico;
String id_ingenico;
boolean active_ingenico;
long lastPushTime;
}
#Data
#Document(collection = "generic_device_config")
public class GenericDeviceConfig {
#Id
String _id;
String storeCode;
String companyCode;
long updated;
boolean enabled;
ArrayList<SerialPort> serialPorts;
String companyId;
GenericIpConfig ipConfig;
}
And this is the request I am sending with POSTMAN:
{
"updated":0,
"enabled":true,
"serialPorts":[],
"companyId":"600",
"companyCode":"0",
"storeCode":"0",
"ipConfig": {
"connection_type":"ETHERNET",
"port": "23",
"port_ingenico": "",
"ip": "192.168.10.55",
"ip_ingenico": "",
"id_ingenico": "",
"active_ingenico": false,
"lastPushTime": 0
}
}
For some reason, I keep getting the following error:
JSON parse error: Unrecognized field \"connection_type\" (class it.igesa.monitoringsystem.model.mongo.device.config.GenericIpConfig), not marked as ignorable; nested exception is com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field \"connection_type\" (class it.igesa.monitoringsystem.model.mongo.device.config.GenericIpConfig), not marked as ignorable (0 known properties: ]
I feel like my code is missing something, since this is the first time I am working with SpringBoot/MongoDB;
It looks as if Jackson can't recognise setter methods for fields, because they don't follow java naming conventions. Try fixing the unrecognised fields with this annotation - #JsonProperty("property_name_here"), by putting it on the setters.
You are also mixing them, some of your fields are named something_something, while others are somethingSomething, which is the standard java way. It's a good idea to pick one and stick to it for the project.
You should also read up on serialization with jackson documentation, annotation examples.
Finally I found the solution. Defining setters and getters annotations for the nested class solved the problem.
I had an extra getter method in a class that I was reusing.
It worked fine when I removed the extra getter.
I hope you find this useful too.
Thanks a lot.

Customising Spring Boot Exception Handling to Prevent Stacktraces Being Returned in Rest Response

How do I configure my spring boot service so that errors such as 500 don't potentially leak implementation details such as stacktraces.
{
"timestamp": "2019/05/01 15:06:17",
"status": 500,
"error": "Internal Server Error",
"message": "Type definition error: [simple type, class net.i2p.crypto.eddsa.math.ed25519.Ed25519LittleEndianEncoding]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class net.i2p.crypto.eddsa.math.ed25519.Ed25519LittleEndianEncoding and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.Collections$UnmodifiableRandomAccessList[0]->........)",
"path": "/api/test"
}
Note: here the stacktrace is in the message and not the exception part of the json.
As you can see I am already formatting the timestamp with:
#Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
private static final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static final String TIMESTAMP = "timestamp";
#Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
//Let Spring handle the error first
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
//Format & update timestamp
Object timestamp = errorAttributes.get(TIMESTAMP);
if(timestamp == null) {
errorAttributes.put(TIMESTAMP, dateFormat.format(new Date()));
} else {
errorAttributes.put(TIMESTAMP, dateFormat.format((Date)timestamp));
}
return errorAttributes;
}
}
But I need to handle the message too.
If this 500 was the only error I could just do:
errorAttributes.put("message", "Server error. Contact support.");
However, all the errors go through here and that would override all the messages.
I could check if the status is 500 and only modify it then. However, there are other errors that can be generated that also might leak stacktraces.
Using #RestControllerAdvice seems to require knowing every exception that is generated and having an #ExceptionHandler for each and knowing which status code to respond with.
Is there a cleaner way to handle this?
It may not be the "cleanest" approach, but with projects I've been on we had a "standard format" for our Error Responses across projects, so we had a custom object with the fields that matched our orgs standard (HttpStatus, Reason, ect.) that extended RuntimeException. Then in our controllers, services, repos, ect we would catch exceptions and create this object accordingly and throw the custom one up instead. Based upon where it happened in the app (repo, service, controller, ect.) we could give our own custom verbage to it, but still log out the full exception in our server logs so we could investigate later
For example if we caught an error in our repository we would create our custom error object, set the Reason to DB unavailable (really all the consumer needs to know), set the status to HttpStatus.SERVICE_UNAVAILABLE (we tracked these with reasons and httpstatus with enums to keep status the same across modules), and throw the custom object up to the controller to be returned.
Sorry if this was a longwinded answer that may not give you what you want, I'm not too familiar with how you're trying to do it so figured I'd just give an example of other methods. I'll put some sample code as well
Custom Exception:
data class MyException(
val reason: String,
val httpStatus: HttpStatus? = null
) : RuntimeException(reason)
Method for creation:
fun createApiException(errorCode: ErrorCodeEnum) = MyException(
reason = errorCode.reason,
httpStatus = errorCode.httpStatus,
)
Spring-boot provides us with a standard method to handle exceptions using spring aop concept. You can use the #ControllerAdvice and #Exceptionhandled annotations to handle exceptions from a spring-boot rest endpoint so that a custom exception is always thrown from a rest endpoint with proper error code and error response.
The #ResponseStatus() annotation can be used to customize the response code being thrown.
For example consider the custom exception :
#ResponseStatus(HttpStatus.NOT_FOUND)
public class DataNotFoundException extends RuntimeException {
public DataNotFoundException(String exception) {
super(exception);
}
}
We can throw this error from a rest GET mapping when a data is not found like :
#GetMapping("/trains/{id}")
public Resource<Student> retrieveTrains(#PathVariable long id) {
Optional<Trains> trains = trainRepository.findById(id);
if (!train.isPresent())
throw new DataNotFoundException("id-" + id);
Resource<Trains> resource = new Resource<Trains>(train.get());
ControllerLinkBuilder linkTo = linkTo(methodOn(this.getClass()).retrieveAllTrains());
resource.add(linkTo.withRel("all-trains"));
return resource;
}
Default error response provided by Spring Boot contains all the details that are typically needed.
However, you might want to create a framework independent response structure for your organization. In that case, you can define a specific error response structure.
For example :
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
super();
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
To use this error node we use :
#ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(DataNotFoundException.class)
public final ResponseEntity<ErrorDetails> handleUserNotFoundException(DataNotFoundException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
#ExceptionHandler(DataNotFoundException.class) indicates that this
method would handle exceptions of the specific type.
new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND) - Create an
error response object and return it with a specific Http Status.
For a more generalized exception handler you can define a method that handles exception of the type Exception.class, that way you don't have to know every exception.
Like :
#ExceptionHandler(Exception.class)
public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
Reference from : https://www.javaguides.net/2019/02/spring-boot-2-angular-7-crud-example-tutorial.html

Function in drools rule file

I have a simple POJO, which has a String field
public class InputFilter {
String email;
}
And this is the DRL file
function void printEmail(String email) {
System.out.println(email);
}
rule "PrintEmail"
when
InputPayload(eval(printEmail(inputFilter.email)))
then
end
Here I get the error as
text=Rule Compilation error inputFilter.email cannot be resolved to a type
This should be simple. I am not sure what I am missing here. I have imported all the required classes. Also, it can understand the type when I do something like inputFilter.email != null.

Unit testing an implementation of IExpectException

I've created an expected exception attribute by implementing the NUnit.Framework.IExpectException interface, as documented there (http://www.nunit.org/index.php?p=exception&r=2.6.2 ) and it works pretty well. It validates that the thrown exception is of the right type and validates the value of some properties on the exception.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class ExpectedHttpErrorExceptionAttribute : ExpectedExceptionAttribute, IExpectException
{
public HttpStatusCode StatusCode { get; set; }
public ExpectedHttpErrorExceptionAttribute()
:base(typeof(HttpError))
{}
public ExpectedHttpErrorExceptionAttribute(HttpStatusCode statusCode)
:this()
{
StatusCode = statusCode;
}
public void HandleException(Exception ex)
{
Assert.That(ex, Is.TypeOf(ExpectedException), "Expected exception of type '{0}' but an exception of type '{1}' has been throwned.", typeof(HttpError).FullName, ex.GetType().FullName);
var httpStatusCode = ((HttpError) ex).StatusCode;
Assert.That(httpStatusCode, Is.EqualTo(StatusCode), "Expected status code '{0}' but was '{1}'.", StatusCode, httpStatusCode);
}
}
My problem is that I want to unit test that attribute, but I can't figure a way to test the following case :
A unit test that have the attribute should fail if no exception are thrown.
I just can't figure a way to write a unit test for that case, since the HandleException is not called when no exception are thrown.
Any suggestion?
The reason you are failing to write a test here is that you are trying to test functionality which is out of responsibility of your class.
Your class validates the exception only in case if exception is thrown. When there is no exception thrown there is nothing to validate :)
It is responsibility of test runner (NUnit or some another) to fail the test when test method is decorated with ExpectedExceptionAttribute (or inherited attribute) and there is no exception thrown during test.
So, you don't need to write a test fot such a scenario.

Assert exception from NUnit to MS TEST

I have some tests where i am checking for parameter name in exception.
How do i write this in MS TEST?
ArgumentNullException exception =
Assert.Throws<ArgumentNullException>(
() => new NHibernateLawbaseCaseDataLoader(
null,
_mockExRepository,
_mockBenRepository));
Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
I have been hoping for neater way so i can avoid using try catch block in the tests.
public static class ExceptionAssert
{
public static T Throws<T>(Action action) where T : Exception
{
try
{
action();
}
catch (T ex)
{
return ex;
}
Assert.Fail("Expected exception of type {0}.", typeof(T));
return null;
}
}
You can use the extension method above as a test helper. Here is an example of how to use it:
// test method
var exception = ExceptionAssert.Throws<ArgumentNullException>(
() => organizations.GetOrganization());
Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
Shameless plug, but I wrote a simple assembly that makes asserting exceptions and exception messages a little easier and more readable in MSTest using Assert.Throws() syntax in the style of nUnit/xUnit.
You can download the package from Nuget using: PM> Install-Package MSTestExtensions
Or you can see the full source code here: https://github.com/bbraithwaite/MSTestExtensions
High level instructions, download the assembly and inherit from BaseTest and you can use the Assert.Throws() syntax.
The main method for the Throws implementation looks as follows:
public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
{
try
{
task();
}
catch (Exception ex)
{
AssertExceptionType<T>(ex);
AssertExceptionMessage(ex, expectedMessage, options);
return;
}
if (typeof(T).Equals(new Exception().GetType()))
{
Assert.Fail("Expected exception but no exception was thrown.");
}
else
{
Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
}
}
More info here.
Since the MSTest [ExpectedException] attribute doesn't check the text in the message, your best bet is to try...catch and set an Assert on the exception Message / ParamName property.