Reputation: 25
I have a Spring MVC service method to execute save() and update() - two operations.
After save() is successfully executed, if I find the user to update does not exist, I will manually throw a new RuntimeExceotion() to rollback the save operation. In this case, how could I return the Error Message("can't find the user") to browser side?
@Transactional(rollbackFor = { Exception.class })
public Map<String,Object> service(){
Map<String,Object> map = new HashMap<String,Object>();
//1. save user
User user = getUser();
this.save(user);
//2. try to update another
String anotherUserId = "anUserId";
User anUser = this.getById(anotherUserId);
if(anUser != null){
anUser.setName("newName");
this.update(anUser);
map.put("status",true);
}else{
//logical error
map.put("status",false);
map.put("err_msg","cant find the user for update");
//triger rollback(rollback save user)
throw new RuntimeException("update user error");
}
return map;
}
Upvotes: 0
Views: 904
Reputation: 3917
You can add an CustomException
class which contain your error msg.
you can send back error msg to your client. For that you can make your service which return type would be Object that's why it can send an Map
or ErrorMessage
.
CustomException
class looks something like that:
public class CustomException extends Exception implements Serializable {
public CustomException(String errorMsg)
{
super(errorMsg);
}
public CustomException(Throwable cause){
super(cause);
}
public CustomException(String message ,Throwable cause){
super(message,cause);
}
}
you can use this by:
throw new CustomException("Can not find the user");
Upvotes: 0
Reputation: 5701
Why don't you wrap your errors in an Object and pass that to the Exception while throwing it.
Later at the controller/request-response handler layer, get the Error object from the Exception and pass that to UI layer.
Class CustomException extends Exception {
Map<String,Object> errorMap;
public CustomException(String errorMsg, Map errorMap)
{
super(errorMsg);
this.errorMap = errorMap;
}
public CustomException(Throwable cause){
super(cause);
}
public CustomException(String message ,Throwable cause){
super(message,cause);
}
}
While Throwing the exception:
throw new CustomException("Can not find the user", map);
In the Controller End, Catch this exception and extract the ErrorMap which contains your data. Wrap/Convert this Object and pass it to UI/Browser.
Upvotes: 1