Best practice to send response in spring boot - spring

I'm coding REST Api-s in spring boot. I want to make sure that my code is readable to front-end developers using swagger API development tool (Swagger). For example
#GetMapping("/getOne")
public ResponseEntity<?> getOne(#RequestParam String id) {
try {
return new ResponseEntity<Branch>(branchService.getOne(id), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<FindError>(new FindError(e.getMessage()), HttpStatus.BAD_REQUEST);
}
}
If the request is successful, response is a Branch object, if fails, the response is a FindError object which has only one attribute (message). So both can be carried out depends on the response. But the swagger UI doesn't show how the response should be shown, because I use "?" as generic type. Is this a best practice to catch an error? (This coding documentation swagger is not useful to front-end developers since it doesn't show the response object). Or any best practice for the above problem?
There are a lot of method which return different object like Branch. Thanks in advance

First of all you should follow the best practices of a RESTful API . Don't use verbs, instead use nouns as URL.So instead of #GetMapping("/getOne") , you can write
it as #GetMapping("/branch/{id}") .
You can refer this blog https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/
#2ndly , Don't return a generic type as ? , instead you can user the specific type , here as Branch and do central exception handling .
The following code snippet can help you :
#GetMapping("/branch/{id}")
public ResponseEntity<Branch> getBranch(#Pathvariable String id) {
{
Branch branch = branchService.getOne(id);
if(branch == null) {
throw new RecordNotFoundException("Invalid Branch id : " + id);
}
return new ResponseEntity<Branch>(branch, HttpStatus.OK);
}
RecordNotFoundException.java
#ResponseStatus(HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends RuntimeException
{
public RecordNotFoundException(String exception) {
super(exception);
}
}
CustomExceptionHandler.java
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler
{
#ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Server Error", details);
return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
#ExceptionHandler(RecordNotFoundException.class)
public final ResponseEntity<Object> handleRecordNotFoundException(RecordNotFoundException ex, WebRequest request) {
List<String> details = new ArrayList<>();
details.add(ex.getLocalizedMessage());
ErrorResponse error = new ErrorResponse("Record Not Found", details);
return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}
}
ErrorResponse.java
public class ErrorResponse
{
public ErrorResponse(String message, List<String> details) {
super();
this.message = message;
this.details = details;
}
private String message;
private List<String> details;
//Getter and setters
}
The above class handles multiple exceptions including RecordNotFoundException and you can also customize for payload validations too.
Test Cases :
1) HTTP GET /branch/1 [VALID]
HTTP Status : 200
{
"id": 1,
"name": "Branch 1",
...
}
2) HTTP GET /branch/23 [INVALID]
HTTP Status : 404
{
"message": "Record Not Found",
"details": [
"Invalid Branch id : 23"
]
}

I would recommend to do it like this .
#GetMapping("/getOne")
public Response getOne(#RequestParam String id) {
ResponseEntity<Branch> resbranch;
ResponseEntity<FindError> reserror;
try {
resbranch=new ResponseEntity<Branch>(branchService.getOne(id), HttpStatus.OK);
return Response.status(200).entity(resbranch).build();
} catch (Exception e) {
reserror=new ResponseEntity<FindError>(new FindError(e.getMessage()), HttpStatus.BAD_REQUEST);
return Response.status(400).entity(reserror).build();
}
}
200 is for OK and 400 is for bad request. Here there wont be anymore ambiguous types..

Related

Spring Can't recognise application.proerties file. Unable to display the configuration defines in property file

I'm trying to display my custom message while handling the exception. But I'm getting no response in the Postman. Here is code snippet that I've used
So, Here is my controller class method
#GetMapping(value="/customers/{customerId}")
public ResponseEntity<Customer> getCustomerById(#PathVariable Integer customerId) throws Exception
{
try {
Customer customer = customerService.getCustomer(customerId);
ResponseEntity<Customer> response = new ResponseEntity<Customer>(customer, HttpStatus.OK);
return response;
}
catch(Exception e)
{
throw new ResponseStatusException(HttpStatus.NOT_FOUND,environment.getProperty(e.getMessage()),e);
}
}
here is my service layer method that I'm calling from getCustomerById method -
#Service(value = "CustomerService")
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerDao customerDao;
#Override
public Customer getCustomer(Integer customerId) throws Exception {
Customer customer = customerDao.getCustomer(customerId);
if (customer == null) {
throw new Exception("Service.CUSTOMER_UNAVAILABLE");
}
return customer;
}
here is my property file
server.port=3557
Service.CUSTOMER_ALREADY_EXIST=Customer already present.Add customer with different attributes.
Service.CUSTOMER_UNAVAILABLE=Customer Details not found. Give valid customer details.
Postman response -
{
"timestamp": "2021-05-02T10:21:22.455+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "",
"path": "/DemoBank/customers/8"
}
That's because you throw an exception instead of returning your custom response. Spring's exception always returns 500.
Change this line:
throw new ResponseStatusException(HttpStatus.NOT_FOUND,environment.getProperty(e.getMessage()),e);
to this:
return new ResponseEntity<>(environment.getProperty(e.getMessage()), HttpStatus.NOT_FOUND);

Send the response as key value pair from Spring controller?

In our application we are getting the request object from third party as form data. We are processing the form data in Spring controller and send the response back. In spring controller we have wrote the logic like below.
#RequestMapping(value = "/oci/html/setup", method = RequestMethod.POST,
produces = {MediaType.TEXT_HTML_VALUE }, consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE })
#ResponseStatus(value= HttpStatus.OK)
#ResponseBody
public String handleOciSetUpRequest1(OciSetupRequest reqObject)
{
if (LOG.isDebugEnabled())
{
LOG.debug("Oci Setup Request Object: " + reqObject.toString());
}
final OciSetupResponse response = getOciService().processOciSetUpRequest(reqObject);
return response.toString();
}
Request Object:
identity: 1234
sharedSecret: password
Expected Response object:
SessionId=1236547878
URL=https://sample.com
Here we need to send the response in the form of key value pair html response. Anyone can help on this
How to send the html response as key-value pair from Spring controller.
If sample code provided will be appreciated....
Thanks in advance
I see that you try to return in a response body, the best would be by means of a rest controller, and also add exception handling, with what you would have:
#RestController
public class SomeClassController {
#PostMapping("/oci/html/setup")
public ResponseEntity<?> reportRecords(OciSetupRequest reqObject) {
Map<String, Object> response = new HashMap<>();
try {
if (LOG.isDebugEnabled())
{
LOG.debug("Oci Setup Request Object: " + reqObject.toString());
}
final OciSetupResponse response = getOciService().processOciSetUpRequest(reqObject);
response.put("SessionId", "1236547878");
response.put("URL", "https://sample.com");
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
response.put("message", e.getMessage());
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Use a map:
#ResponseBody
public Map<String, String> handleOciSetUpRequest1(OciSetupRequest reqObject)
{
if (LOG.isDebugEnabled())
{
LOG.debug("Oci Setup Request Object: " + reqObject.toString());
}
final OciSetupResponse response = getOciService().processOciSetUpRequest(reqObject);
Map<String, String> responseMap - new HashMap();
map.put("SessionId", "someValue");
map.put("URL", "someValue");
return responseMap;
//returns JSON {"SessionId":"someValue", "URL":"someValue"}
}

How to correctly handle exceptions from the service (spring boot rest)

When building a rest api using spring boot what is the best way to handle exceptions from the service level and pass them to the controller, so the client gets a custom json error message.
{
"message": "some error"
}
Endpoint from controller
#PostMapping("/login")
public String login(#RequestBody #Valid LoginDto loginDto) {
return gson.toJson(userService.login(loginDto.getUsername(), loginDto.getPassword()));
}
Service level code
public LoginResponseDto login(String username, String password) {
try {
//performs some checks
...
return new LoginResponseDto(token.get());
} catch (AuthenticationException e){
LOGGER.info("Log in failed for user {}", username);
}
return new LoginResponseDto("login failed");
}
LoginResponseDto class
String token;
String message;
public LoginResponseDto(String message) {
this.message = message;
}
Currently it is obviously returning the correctly message but not the correct status code, it will show status 200 with the error message in json.
You have some options:
1) Returning a message:
If you want to return a message something like this,
{
"message": "some error"
}
What you can do is:
Option 1: Create a custom POJO class for error message and return the reference to the object of that POJO class.
Something like this:
ErrorMessage.java
package org.example;
public class ErrorMessage {
private String message;
public ErrorMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Request Handler Method in Controller:
#GetMapping("/login{?username, password}")
public ErrorMessage isUserAuthenticated(#RequestParam String username, #RequestParam String password) {
if (username.toLowerCase().contentEquals("root") && password.contentEquals("system")) {
return new ErrorMessage("authenticated");
}
return null;
}
Option 2: Create a Map and insert key-value pairs that you want to have in the message.
Like this:
#GetMapping("/login{?username, password}")
public Map<String, String> isUserAuthenticated(#RequestParam String username, #RequestParam String password) {
Map<String, String> message = new HashMap<>();
if (username.toLowerCase().contentEquals("root") && password.contentEquals("system")) {
message.put("message", "authenticated");
}
return message;
}
2) Returning an error status code (highly recommended by me):
You may use ResponseEntity for this purpose.
#GetMapping("/login{?username, password}")
public ResponseEntity<?> isUserAuthenticated(#RequestParam String username, #RequestParam String password) {
if (username.toLowerCase().contentEquals("root") && password.contentEquals("system")) {
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

Response error format with manual validation in Spring Data Rest

When using Spring Data REST and JSR 303 Bean Validation I get a response like the following when there's a constraint violation:
{
"errors": [
{
"entity": "Empresa",
"property": "observacao",
"invalidValue": "",
"message": "O tamanho do campo deve ser entre 1 e 255"
}
]
}
But I'm trying to validate an object manually, and I would like to return the validation errors in the same format used by Spring Data Rest.
#DeleteMapping("/departamento/{id}")
public #ResponseBody
ResponseEntity<?> filtro(#PathVariable Long id){
Optional<Departamento> departamentoOpt = this.departamentoRepository.findById(id);
if (!departamentoOpt.isPresent()) {
return ResponseEntity.notFound().build();
}
Departamento departamento = departamentoOpt.get();
BindingResult errors = new BeanPropertyBindingResult(
departamento, "departamento");
this.validator.validate(departamento, errors, PreDeleteValidation.class);
if (errors.hasErrors()) {
// How to return a response in the same format used by SDR here?
}
return ResponseEntity.ok().build();
}
How can this be accomplished?
You can throw and Exception on validation failure and register a Spring MVC Controller Advice to catch this and transform it to something that meets your needs.
if (errors.hasErrors()) {
throw new org.springframework.web.bind.MethodArgumentNotValidException(
departamento, bindingResult)
}
The advice could look something like the below:
#ControllerAdvice
public class ErrorHandlingAdvice
{
#ExceptionHandler(MethodArgumentNotValidException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
#ResponseBody
public ValidationError processValidationError(MethodArgumentNotValidException ex)
{
ValidationError error = new ValidationError();
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
for (FieldError fieldError : fieldErrors)
{
error.addError(fieldError.getField(), fieldError.getDefaultMessage());
}
return error;
}
}
ValidationError is just a simple bean:
public class ValidationError
{
private final Map<String, List<String>> errors;
public ValidationError()
{
errors = new TreeMap<>();
}
public void addError(String field, String error)
{
if (!errors.containsKey(field))
{
errors.put(field, new ArrayList<String>());
}
errors.get(field).add(error);
}
public Map<String, List<String>> getErrors()
{
return errors;
}
}

Spring MVC ExceptionHandling: action annotated as #ExceptionHandling can't pass variable to error view

I know a lot of people have had issues similar to this.Sorry posting it again, but i believe there is something i might not be doing well.
I'm using Spring 3.0.5 with freemarker 2.3.14. Basically i wanted to show a friendly error message to the user.
#Controller("exceptioncontroller")
public class ExceptionController {
private static Logger logger = Logger.getLogger(ExceptionController.class);
#RequestMapping(value = "/site/contentnofoundexception")
public String throwContentFileNotFound(){
boolean exception = true;
if(exception){
throw new ContentFileNotFoundException("content ZZZ123 not found");
}
return "errortest";
}
#ExceptionHandler(value = ContentFileNotFoundException.class)
public String handleFileNotFoundException(ContentFileNotFoundException ex, Model model) {
model.addAttribute("msg",ex.getErrorMessage());//this message is never passed to the error view. msg is always null
return "error";
}
}
//same issue for handleException action which uses ModelAndView
#ExceptionHandler(value = Exception.class)
public ModelAndView handleException(Exception ex){
logger.error(ex);
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
String message = "Something Broke. Please try again later";
mv.addObject("msg", message);
return mv;
}
// Custom Exception class
public class ContentFileNotFoundException extends RuntimeException {
private String errorMessage;
public ContentFileNotFoundException(String message) {
this.setErrorMessage(message);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
So each case either handleFileNotFoundException or handleException actions are called alright but they can't send any message to the error.ftl view to display to the user. Is there anything i need to configure?
Thanks for helping in advance

Resources