Как вернуть сообщение об ошибке в тексте JSON, когда мой простой REST get не удался? - PullRequest
0 голосов
/ 21 апреля 2020

Я создаю веб-приложение с Bootstrap, jQuery и Spring MVC.

У меня определен веб-сервис, который выглядит следующим образом и работает нормально ... Пользователь объект возвращается в формате JSON.

Однако при возникновении ошибки я хотел бы вернуть что-то похожее на это ...

{
  "success": false,
  "message": "Unable to retrieve user for id '55'; Could not connect to database."
}

... так Я могу разобрать сообщение об ошибке и отобразить его в хорошем предупреждении.

Я пытался вызвать исключение, но это не сработало. Что еще я должен попробовать? Вот код ...

@RestController
public class UserController {

/* ... */

    @RequestMapping(value = "/json/user/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(@PathVariable("userId") int userId) throws Exception {
        boolean bSuccess = false;
        String errorMsg = "";

        User user = null;
        try {
            user = userService.getUser(userId);
            bSuccess = true
        } catch (Exception x) {
            bSuccess = false;
            errorMsg = "Unable to retrieve user for id '"+userId+"'; "+x.getMessage();
        }

        // Need something here; 
        // if (!bSuccess) {
        //    return json error message ??
        // }

        return user;
    }

/* ... */

}

Ответы [ 2 ]

1 голос
/ 21 апреля 2020

Вы можете использовать пружину, чтобы сделать это:

вот так:

@RestController
public class UserController {

/* ... */

    @RequestMapping(value = "/json/user/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getUser(@PathVariable("userId") int userId) throws Exception {

    ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());

        User user = null;
        try {
            user = userService.getUser(userId);
            modelAndView.addObject("data", user);
            modelAndView.addObject("msg", "Inser yout msg");
            modelAndView.setStatus(HttpStatus.OK);

        } catch (Exception x) {

            modelAndView.addObject("error", x);
            modelAndView.addObject("msg", ""Unable to retrieve user for id 
                         '"+userId+"'; "+x.getMessage();");
            modelAndView.setStatus(HttpStatus.BAD_REQUEST);

        }


        return modelAndView ;
    }

/* ... */

}
````


I believe that this way is better. So you can standardize the responses using the ModelEndView. Look in <https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html>
0 голосов
/ 21 апреля 2020

ExceptionHandler поможет в этом случае.

Exception. java

public class Exception {

    private boolean success;
    private String message;
//....
}

ExceptionHandler. java

@RestControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {

        Exception ex = new Exception();
        ex.setSuccess(false);
        ex.setMessage("Unable to retrieve user for id....");
        return new ResponseEntity(ex,HttpStatus.NOK);
    }
}

Итак, при любом исключении происходит, он придет к этому методу.

Надеюсь, это поможет !!

...