18496

How to get spesific error instead of Internal Service Error

Question:

I am getting Internal Server Error on postman even though I am throwing custom exception from my code exception. I want to see the exception having valid error message and error code, what I am throwing. It will be a great help if anyone of you can help me on this point. Like how I can get better error message. Adding below code snap. Thanks in advance

@Service public class FetchActionImpl implements FetchAction { private static Logger log = LoggerFactory.getLogger(FetchActionImpl.class); @Autowired FetchActionServiceImpl fetchActionService;// = new FetchActionServiceImpl(); @Override public FetchResponse fetchActionRequest(String caseId) throws BBWException,Exception{ //String resp =""; log.info("fetchaction Request: {}",ApplicationConstants.LOG_ENTRY_MESSAGE); log.info("The caseId received from BRASS:\n {}",caseId); FetchResponse resp = null; try{ if(true) { throw new BBWException("500","Test"); } resp = fetchActionService.fetchIt(caseId); log.debug("fetchaction Response: {}",resp.toString()); } catch (BBWException be) { throw be; } catch (Exception e) { throw new BBWException("500",e.getMessage()); } return resp; } } @Api @Path("/fetch_service") public interface FetchAction { @GET @Path("/fetchaction/caseid/{caseid}") @Produces({MediaType.APPLICATION_JSON}) //@Consumes({MediaType.TEXT_XML}) @ApiOperation( value = "Respond BRASS Request", notes = "Returns a XML object " ) @ApiResponses( value = { @ApiResponse(code = 404, message = "Service not available"), @ApiResponse(code = 500, message = "Unexpected Runtime error") }) public FetchResponse fetchActionRequest(@PathParam("caseid") String caseid) throws BBWException, Exception; }` public class BBWException extends Exception { private static final long serialVersionUID = -7987978270260338068L; private String errorCode; private String errorMessage; public BBWException(String errorCode, String errorMessage) { super(errorMessage); this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMessage() { return errorMessage; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } @Override public String toString() { return (this.errorCode + " " + this.errorMessage); }

}

Answer1:

Each time the (uncaught) exception is throw, SpringBoot returns Http-500 Internal Server Error. There are many ways of handling exceptions in Spring.

Let's say I have my controller and I implicitly throw an exception.

@RestController public class HelloWorldController { @GetMapping("/hello-world") public String helloWorld() { throw new MyCustomException("I just can't say hello!"); } }

It's the same as yours - you can specify anything in the exception.

<strong>First:</strong>

One of the way of handling it, is to create a class with @ControllerAdvice annotation.

@ControllerAdvice public class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(MyCustomException.class) public ResponseEntity<String> handlyMyCustomException(MyCustomException e) { logger.error("error occurred {}", e); return new ResponseEntity<>("Something happened: " + e.getMessage(), HttpStatus.I_AM_A_TEAPOT); } }

This way you are able to catch the exception of your choice (globally) and return the message with the HTTP Response Status of your choice, not neccessarily I_AM_A_TEAPOT

<strong>Second:</strong>

@ExceptionHandler(MyCustomException.class) public ResponseEntity<String> handlyMyCustomException(MyCustomException e) { logger.error("error occurred {}", e); return new ResponseEntity<>("Something happened: " + e.getMessage(), HttpStatus.I_AM_A_TEAPOT); }

You could also create only method annotated with @ExceptionHandler in your controller class - but this is not global and is going to work only for this exact controller calls.

Result below:

<a href="https://i.stack.imgur.com/FZwxV.png" rel="nofollow"><img alt="That's the result" class="b-lazy" data-src="https://i.stack.imgur.com/FZwxV.png" data-original="https://i.stack.imgur.com/FZwxV.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

<strong>Third:</strong>

Another way of dealing with exceptions is to create your own error .html files. If you place a file in resources/static/error/500.html it should be returned when the Http-500 Internal Server Error is thrown.

Recommend

  • Does ::TIMESTAMP::DATE work in javaspring?
  • Javascript replace() method failing?
  • I cannot disable link on non-zero date
  • Sympy-numpy integration exists - where is it documented?
  • Does mongoose / mongodb have access to object references in schema during aggregate?
  • How to navigate to other page without animation Flutter
  • What is the meaning of 'controlAggregation' in the SAPUI5 routing configuration?
  • List all possible paths using lodash
  • Make div NOT auto stretch to container width
  • Is there a generic swap method in the framework?
  • Implements ViewHolder on a ListView AndroidStudio
  • compile error with hadoop-yarn-server-nodemanager
  • How to create the matrix from data frame?
  • LCS ALGORITHM ( example )
  • How to implement 'if' in Gherkin
  • How to bend a cylinder in three.js?
  • Decimal to ASCII Conversion [closed]
  • plot dirac function in matlab
  • Auto send email based on the time and email address in database
  • Defer unused CSS
  • JavaMail connection problems [duplicate]
  • Add checkbox dynamically using angular 2
  • Ajax call on Multiple selection in Select box
  • using maven pom while creating jar:test-jar some times it says JAR will be empty - no content was ma
  • Why is ordered choice in pyparsing failing for my use case?
  • How to configure the APNS.Certificate in the arm template
  • Neo4j…how to get a visual representation of my data?
  • Geokit in Ruby on Rails, problem with acts_as_mappable
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • Why isn't stemDocument stemming?
  • Google App Engine Datastore: Dealing with eventual consistency
  • How to handle div that is created dynamically in a table
  • How to get rgb from transparent pixel in js
  • Background transfer download task failed when app was closed
  • Bitrate JWplayer
  • Capture SIGFPE from SIMD instruction
  • Using Service Component Runtime
  • How do I use TagLib-Sharp to write custom (PRIV) ID3 frames?
  • Write to .csv file with PHP (Commas in Data Error)
  • CAS 4 - Not able to retrieve the LDAP groups after successful authentication