In Java SE it is possible set the cause of an exception using initCause to avoid losing information about the error when catching and rethrowing an exception. Is it possible to do the same in Java ME?
It is easy to extend the Exception class to achieve this:
public class OperationFailedException extends Exception{
public Exception cause;
public OperationFailedException(String string, Exception ex) {
super(string);
cause=ex;
}
public void printStackTrace(){
super.printStackTrace();
System.err.println("\nCaused by:\n");
cause.printStackTrace();
}
}
This exception is useful for hiding the underlying exceptions, such as when we want to avoid dependancies or when we want to avoid forcing the caller to deal with too many types of exceptions. I generally also create a version of this class extending RuntimeException for wrapping exception that I want to be unchecked
Related
I'm trying to write a simple Spring Boot controller that renders a GORM instance and failing.
Here's a shortened version of my code:
#RestController
#RequestMapping("/user")
class UserController {
#RequestMapping(value='/test', method=GET)
User test() {
return new User(username: 'my test username')
}
}
I get the following error message:
Could not write JSON: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.springframework.validation.DefaultMessageCodesResolver and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: users.domain.User["errors"]->grails.validation.ValidationErrors["messageCodesResolver"])
The error seems to be caused by extra properties injected by GORM. What is the proposed solution for this? Will this eventually be solved in gorm-hibernate4-spring-boot? Should I simply disable SerializationFeature.FAIL_ON_EMPTY_BEANS (I don't have a lot of experience with Jackson so I'm not entirely sure what side effects this may have)? Should I use Jackson's annotations to solve the problem? Any other options?
I've found a way to get rid of the error using this code:
#Component
class ObjectMapperConfiguration implements InitializingBean {
#Autowired
ObjectMapper objectMapper
#Override
void afterPropertiesSet() {
def validationErrorsModule = new SimpleModule()
validationErrorsModule.addSerializer(ValidationErrors, new ErrorsSerializer())
objectMapper.registerModule(validationErrorsModule)
}
}
class ErrorsSerializer extends JsonSerializer<ValidationErrors> {
#Override
void serialize(ValidationErrors errors, JsonGenerator jgen, SerializerProvider provider) {
jgen.writeStartObject()
jgen.writeEndObject()
}
}
Obviously this solution is far from perfect as it simply nukes all validation errors but right now it is good enough for me. I am pretty sure the Spring Boot team will have to address this issue eventually as the GORM objects are also being serialized with some internal Hibernate properties like attached. I'm not accepting this answer as it is not an acceptable solution for most scenarios, it basically just squelches the exception.
This did not work for me.
So I used this instead and the error disappeared.
#JsonIgnoreProperties(["errors"])
I'm using springBootVersion '1.4.1.RELEASE' with gorm & hibernate5:
compile("org.grails:gorm-hibernate5-spring-boot:6.0.3.RELEASE")
I am having to include the following at the top of each domain class in order to use them in a client response (i.e. json serialization using jackson):
#JsonIgnoreProperties(["errors", "metaClass", "dirty", "attached", "dirtyPropertyNames"])
When using springBootVersion '1.3.5.RELEASE' I was able to get away with:
#JsonIgnoreProperties(["errors"])
This is trending in the wrong direction :)
I would like to know if the following is possible with JSF2.
When my business classes or DAO classes are throwing a certain exception (e.g. a custom exception called BusinessException) a FacesMessage gets added to the current page with a standard message string for this exception class. The business classes and the managed beans are in two different projects. Only the managed beans have access to the business classes.
You can use a snippet like this in your managed bean:
try
{
... do your staff here ...
} catch (YourBusinessException ex)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Your custom message"));
}
This is a general approach and it will work if your business method throws a YourBusinessException instead of catching it.
You can implement a parent bean from which every single managed bean could extend from. There, implement an access point for each of your service calls.
That solution depends of course in how many service operations you have and if they're reused by diferent managed beans. Apart from that, keep in mind that you could need to handle the exceptions on the parent in other way that could not be just adding a message. That question depends a lot in your current implementation and application type.
Just think about it:
public abstract class ParentBean{
Service service;
public void performOperationAtService(){
try{
service.operation();
}catch(YourBusinessException ex){
FacesContext.getCurrentInstance()
.addMessage(null, new FacesMessage("An error occured. Please contact your administrator"));
}
}
}
#ManagedBean
#ViewScoped
public class ConcreteBean extends ParentBean{
public void someAction(){
//Do some stuff
super.performOperationAtService();
}
}
I am learning ANTLR4 and I have no previous experience with parser generators.
When I define my own visitor implementation, I have to override methods of the BaseVisitor (I am looking for instance at the EvalVisitor class at page 40 of the book). In case my method implementation possibly throws an exception, what should I do? I cannot use a checked exception since the original method has an empty throws clause. Am I expected to use unchecked exceptions? (this seems a bad Java design). For instance, assume that in the EvalVisitor class I want method visitId (page 41) to throw a user-defined exception, say UndefinedId, rather than returning 0. How should I write my code?
You have two options:
Handle the exception inside the visitor method itself.
Wrap your checked exception in an unchecked exception. One possibility is ParseCancellationException, but you'll have to determine for yourself whether or not that makes sense in your application.
try {
...
} catch (IOException ex) {
throw new ParseCancellationException(ex);
}
I want to log exception for all of my methods using AOP. I had created an attribute for the same as following:
[AttributeUsage(AttributeTargets.All)]
public class ClsLogger : System.Attribute
{
private string _exMsg;
public ClsLogger(string exMsg)
{
//
// TODO: Add constructor logic here
//
_exMsg = exMsg;
LogError();
}
public void LogError()
{
// This methods logs exception
// Log Exception
}
}
Finally, I want to use this logging attribute to log exception messages of the methods of my application. How I can pass exception messages to the atrribute as it is not a fixed string but varrible?
Could anybody help on this?
Attributes in C# don't instantiate until you call GetCustomAttributes, and they instantiate every time you do so (see this question here on SO).
If you want to use AOP (as your title indicates), then you'll need to use some framework, like PostSharp, Fody, SheepAspect, etc.
If you are using ASP.NET MVC, then there is a built-in ActionFilter class that you can also use, but only on Controller methods.
I want to be able to support multiple versions of Java ME without having to have multiple builds. I already know how to detect the profile/configuration/supported JSRs. My problem is that knowing whether the JSR is supported at run time doesn't allow me to use all the features as Java-ME does not provide support for reflection.
For if I call a function added in a later version anywhere in the code - even a location that will never be run, then this could cause an error during resolution on some JVMs. Is there any way round this?
Related Questions
Handling optional APIs in J2ME
If you only need to access the class C through an interface which you know you will have access to, then it is simple enough:
MyInterface provider=null;
try{
Class myClass= Class.forName("sysPackage.C");
provider = (MyInterface)(myClass.newInstance());
}catch(Exception ex){
}
if(provide!=null){
//Use provider
}
If C does not have an interface that can be used, then we can instead create a wrapper class S that will be a member of the interface instead.
class S implements MyInterface{
static {
try {
Class.forName("sysPackage.C");
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void forceExceptionIfUnavailable() {}
//TODO: Methods that use C. Class C will only be used within this class
}
S has a static block so that an exception is thrown during class resolution if C is unavailable. Immediately after loading the class, we call forceExceptionIfUnavailable to make sure that the static block is run immediately. If it doesn't crash, then we can use the methods in S to indirectly use class C.
Alternatively, we can use the method here:
Basically, you create a new package P, with a public abstract class A and a concrete subclass S private to the package. A has a static method getS that returns an instance of S or null if an exception is thrown during instantiation. Each instance of S has an instance of C so it will fail to instantiate when C is unavailable - otherwise it will succeed. This method seems to be a bit safer as S (and hence all the C APIs) are package private.