I created API with spring. When I call that API then show error
Here is the Controller class.
#RequestMapping(value={"/dPIUsagePackageInfo"},method=RequestMethod.POST)
public ResponseEntity<DPIUsagePackageInfoRs> dPIUsagePackageInfo(#RequestBody List<DPIUsagePackageInfoRq> dPIUsagePackageInfoRq){
//
DPIUsagePackageInfoRs response = this.ccbsBusiness.dPIUsagePackageInfo(dPIUsagePackageInfoRq);
return new ResponseEntity(response, response.getStatus());
}
Here is the Request class
public class DPIUsagePackageInfoRq {
private List<String> srvName;
public List<String> getSrvName() {
return srvName;
}
public void setSrvName(List<String> srvName) {
this.srvName = srvName;
}
}
I passed this json body
{
"dPIUsagePackageInfoRq" : {
"srvName": ["xxx","rrr","rrrrr"]
}
}
But response like this
{
"resultCode": "000400",
"resultDesc": "ERROR - Bad request; check the error message for details."
}
Where is the wrong with my code.Thanks in advanced.
You are sending only one DPIUsagePackageInfoRq instance where you should be sending it in a list. Please try adding "[" and "]" to start and end of your body so that it becomes a list.
The request which you are sending should be as follows:
[
{
"srvName": ["xxx","rrr","rrrrr"]
}
]
and if you would like to send multiple DPIUsagePackageInfoRq objects, you can use increment the objects like this:
[
{
"srvName": ["xxx","rrr","rrrrr"]
},
{
"srvName": ["xxx","rrr","rrrtrr"]
}
]
Related
I'm getting response from external service that looks like:
"status": {
"httpCode": "external service response code, e.g. 201",
"errors": [
{
"code": "error code, e.g. 13",
"message": "e.g. Invalid value for some variable"
},
{
"code": "12",
"message": "Invalid phone number format"
}
]
}
The errors list may have multiple objects. While returning the response from that external service to my frontend application, I'd like to show all the messages. How do I do that? As far as I know Exception related classes only have a single field called message.
Exceptions are mostly not special, they are just a type definition same as any other. You can have them do whatever you want, as long as they extend Throwable. For example:
public class MaciazServiceException extends Exception {
private final Map<Integer, String> codeToMessageMapping;
public MaciazServiceException(JSON json) {
// code here that pulls code and message apart and makes...
Map<Integer, String> codeToMessageMapping = ....;
this.codeToMessageMapping = codeToMessageMapping;
}
#Override public String getMessage() {
// code here that returns a nice view of the above. For example...
return codeToMessageMapping.entrySet().stream().map(
entry -> entry.getKey() + " = " + entry.getValue())
.collect(Collectors.joining("\n"));
}
// you can define methods too, if you want:
public boolean hasErrorCode(int code) {
return codeToMessageMapping.containsKey(code);
}
}
This can then be used elsewhere:
try {
myMaciazService.doThingie(...);
} catch (MaciazServiceException e) {
if (e.hasErrorCode(MaciazService.ERRORCODE_NOT_AUTHORIZED)) {
userpassView.show();
}
}
One of the way to customize the Http response for exceptions, by using the Custom Exceptions.
1.Create a custom exception by using RuntimeException Class
public class SampleException extends RuntimeException {
private List<SampleNestedObject> messages;
public SampleException() {
}
public SampleException(List<SampleNestedObject> messages){
this.messages=messages;
}
}
public class SampleNestedObject {
private int httpCode;
private String message;
//Getters,Setters,Contructors
}
2.Create a response Structure
public class SampleErrorResponse {
private List<SampleNestedObject> messages;
//Getters,Setters,Contructors
}
Create an ExceptionHandler
#ExceptionHandler(SampleException.class)
public final ResponseEntity<Object> handleSampleException(SampleException ex,WebRequest request){
SampleErrorResponse errorResponse=new SampleErrorResponse(ex.getMessages());
return new ResponseEntity(errorResponse,HttpStatus.NOT_FOUND); //Any status code
}
4.Throw exception whenever you want to.
#GetMapping("/getException")
public ResponseEntity<Object> getException(){
List<SampleNestedObject> messages= Arrays.asList(new SampleNestedObject(404,"Sample Message 1"),new SampleNestedObject(404,"Sample Message 2"));
throw new SampleException(messages);
}
Response for the above sample will be,
{
"messages": [
{
"httpCode": 404,
"message": "Sample Message 1"
},
{
"httpCode": 404,
"message": "Sample Message 2"
}
]
}
Hope this will work.
I am writing some REST apis with swagger-ui . Now during the execution process of this apis I am performing some operation, Which I need to send as a response of the API. Consider the following response as an example:
{
"Database": [
"Table 1 created",
"data 1 inserted",
"Data 3 insertion failed"
],
"Kafka": [
"Topic 1 created",
"Topic 3 deleted",
"Topic 4 rebalanced"
]
}
So is there any framework for this, or I need to manually create the JSON object and send it as a response.
I suppose you are using Spring MVC?
First: create a class for api response.
public class Data {
private List<String> database = new ArrayList();
private List<String> kafka = new ArrayList();
public List<String> getDatabase() {
return database;
}
public void setDatabase(List<String> database) {
this.database = database;
}
public List<String> getKafka() {
return kafka;
}
public void setKafka(List<String> kafka) {
this.kafka = kafka;
}
}
Second: use #ResponseBody annotation against the controller's method. This will make spring understand that method return value should be bound to the web response body.
#ResponseBody
public Data apiMethod() {
return new Data();
}
I have designed login module in RESTFul API using jersey.
whenever any error occurred while login it will return error code and message like,
{
"errorFlag": 1,
"errorMessage": "Login Failed"
}
but whenever I get successful results it returns
{
"apiKey": "3942328b-fa65-496c-bf32-910aafbc1b0e",
"email": "caXXXX#gmail.inl",
"name": "Chandrakant"
}
I'm looking for results like below
{
"errorFlag": 0,
"errorMessage":{
"apiKey": "3942328b-fa65-496c-bf32-910aafbc1b0e",
"email": "caXXXX#gmail.inl",
"name": "Chandrakant"}
}
Use structure like below,
{
status/statusCode : 200/400, //eg. 200 for success, any other for failure.
statusMessage : "Success/<failureMessage>",
errorDetails : "Failed due to <reason>" //optional
data :{ //data will exists only in case of success call.
}
}
you can achieve this like below,
#GET
#Path("/images/{image}")
#Produces("image/*")
public Response getImage(#PathParam("image") String image) {
File f = new File(image);
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
You can return all the attributes in HashMap as key value .
Below piece of code worked for me
#POST
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public HashMap check(InputStream inputJsonObj) {
HashMap map = new HashMap();
map.put("key1", "value1");
return map;
}
Is there any simple methods to return exception in JSON using Rest api?
I've already googled this question, but all solutions i see, was about throwing exceptions during some calculations. But what if income parameters are wrong? I mean what if there is sone string instead of int input parameter?
I created some DTO class for input data:
#XmlRootElement
public class RequestDTO implements Serializable{
private static final long serialVersionUID = 1L;
#XmlElement(name = "request_id")
private String requestId;
#XmlElement(name = "site")
private List<String> sitesIds;
#XmlElement(name = "date_begin")
#JsonSerialize(using = DateSerializer.class)
#JsonDeserialize(using = DateDeserializer.class)
private Date dateBegin;
#XmlElement(name = "date_end")
#JsonSerialize(using = JsonDateSerializer.class)
#JsonDeserialize(using = JsonDateDeserializer.class)
private Date dateEnd;
#XmlElement(name = "volume")
private double volume;
// there is getters and setters
}
If i sent something like 'qwerty' instead of 'volume' field in my json request i'l see error message like Runtime. Is it possible to handle it in someway? I mean to return error in json with such structure?
public class ExceptionDTO {
private String shortExceptionMessage;
private String stackTrace;
public ExceptionDTO(String shotExceptionMessage, String stackTrace){
this.shortExceptionMessage = shotExceptionMessage;
this.stackTrace = stackTrace;
}
public String getShortExceptionMessage() {
return shortExceptionMessage;
}
public String getStackTrace() {
return stackTrace;
}
}
UPD1:
#Provider
#Singleton
public class ExceptionMapperProvider implements ExceptionMapper<Exception>{
#Override
public Response toResponse(final Exception e) {
StringBuilder trace = new StringBuilder();
IntStream.range(0, e.getStackTrace().length)
.forEach(i -> trace.append(e.getStackTrace()[i]).append('\n'));
ExceptionDTO exceptionMessage = new ExceptionDTO(
e.toString(),
trace.toString()
);
return Response.status(500).entity(exceptionMessage).build();
}
}
As it's not really clear if you are interested on checking if field or value of the payload is correct, here are a few ways to work with both.
If you want to check if the value for a field is correct (ie volume field value should be greater than zero etc), check out bean validation. This makes use of annotations on the fields you want to verify.
// for example
#Min(value = 0, message = "invalid message")
private double range;
To use your ExceptionDTO as error response whenever one of those validation fails, you can do so by creating an ExceptionMapper<ConstraintViolationException>. check it here for more details.
If you are checking for the invalid field (ie client sends ragne fields instead of range), have a look at the stack trace on what exception is being thrown. Then register an exception mapper with your ExceptionDTO as body.
For example, if UnrecognizedPropertyException is thrown then you can add:
#Provider
public class UnrecognizedPropertyExceptionMapper implements ExceptionMapper<UnrecognizedPropertyException> {
#Override
public Response toResponse(UnrecognizedPropertyException e) {
ExceptionDTO myDTO = // build response
return Response.status(BAD_REQUEST).entity(myDTO).build();
}
}
If you want to validate input parameters in the request, you should return status code 400 (Bad Request) along with the error details. You can simply send json
{ "error": { "message": "string received for parameter x, where as int expected" } with the response status code 400.
`
I did a bit of research and determined that the best way to encode a Java exception in JSON is to use a convention developed by Oasis that looks like this:
{
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
details is a list that should have an entry for each nested cause exception in the chain.
innererror.trace should include the stack trace if you wish, as a list of string values.
The response status code should be 400 unless you have a good reason for making it something else, and the code in the structure should match whatever you sent.
Write one method to convert a Java exception to this format, and you are done. Use it consistently and your JS code will be able to handle and display the exception values.
More of the details of the other approaches evaluated and dismissed are covered in this blog post on JSON REST API – Exception Handling
https://agiletribe.purplehillsbooks.com/2015/09/16/json-rest-api-exception-handling/
Here is the java method to convert an exception to this format:
public static JSONObject convertToJSON(Exception e, String context) throws Exception {
JSONObject responseBody = new JSONObject();
JSONObject errorTag = new JSONObject();
responseBody.put("error", errorTag);
errorTag.put("code", 400);
errorTag.put("target", context);
JSONArray detailList = new JSONArray();
errorTag.put("details", detailList);
String lastMessage = "";
Throwable runner = e;
while (runner!=null) {
String className = runner.getClass().getName();
String msg = runner.toString();
runner = runner.getCause();
JSONObject detailObj = new JSONObject();
detailObj.put("message",msg);
int dotPos = className.lastIndexOf(".");
if (dotPos>0) {
className = className.substring(dotPos+1);
}
detailObj.put("code",className);
System.out.println(" ERR: "+msg);
detailList.put(detailObj);
}
JSONObject innerError = new JSONObject();
errorTag.put("innerError", innerError);
JSONArray stackList = new JSONArray();
runner = e;
while (runner != null) {
for (StackTraceElement ste : runner.getStackTrace()) {
String line = ste.getFileName() + ":" + ste.getMethodName() + ":" + ste.getLineNumber();
stackList.put(line);
}
stackList.put("----------------");
runner = runner.getCause();
}
errorTag.put("stack", stackList);
return responseBody;
}
I am currently using Play v1.2.3. I have an endpoint to which I want to send a json object which will be deserialized into a Java object. So, I have something that looks like this:
public class UserController extends Controller {
public static class FullName {
public String first;
public String last;
}
public static void putName( FullName name ) { ... }
}
##### routes
PUT /user/name UserController.putName
With that in place, I would hope to call the endpoint with the given javascript:
$.ajax({
type: "PUT",
data: { first: "Michael", last: "Bailey" },
url: "/user/name"
});
Unfortunately, with the above setup, it seems that play is not wanting to send the entire data object, but is instead attempting to populate two parameters (first and last). Is there a way to define the endpoint to consume the complete body directly, or does it have to be done by hand?
To cast the entire input body into a Model class:
public static void create(JsonObject body) {
CaseFolder caseFolder = new Gson().fromJson(body, CaseFolder.class);
caseFolder.user = getConnectedUser();
if(caseFolder.validateAndSave()) {
renderJSON(
new JSONSerializer()
.exclude("*.class")
.exclude("user")
.serialize(caseFolder));
} else
error();
}
Also, the above code takes the resulting Model object and serializes it back out to JSON as the response body.
If you want to just access certain fields within the JSON request, you can use:
public static void update(JsonObject body) {
try {
Long id = (long) body.get("id").getAsInt();
CaseFolder cf = CaseFolder.loadAndVerifyOwner(getConnectedUser(), id);
cf.number = body.get("number").getAsString();
cf.description = body.get("description").getAsString();
if(cf.validateAndSave())
ok();
else
error();
}
catch (NullIdException e) {error();}
catch (NotFoundException e) {notFound();}
catch (NotOwnerException e) {forbidden();}
catch (Exception e) {e.printStackTrace(); error();}
}
Play's action method parameter binding mechanism does not accept JSON. You need to bind it manually. In your example, the code could be something like:
public static void putName( String data ) {
FullName fname = new Gson().fromJSON(data, FullName.class);
...
}
Note, Gson is provided with play!framework distribution, so you are free to use it
With your settings play is expecting params with names "name.first" and "name.last" and you are sending "first" and "last". Try with this ajax post
$.ajax({
type: "PUT",
data: {
name: {
first: "Michael",
last: "Bailey"
}
},
url: "/user/name"
});