在http异常中返回自定义消息

时间:2017-02-13 06:52:58

标签: java spring spring-boot exception-handling

这是我的ExceptionHandler类

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends Exception {

    private static final long serialVersionUID = -1964839652066902559L;

    public NotFoundException(String message) {
        super(message);
    }
}

在我的服务中我有

@Service
public class myService {
 public String getName() throws NotFoundException{
            logger.error("Name not found");
            throw new NotFoundException("Name not found");
        }
}

我得到的回应是:

{
  "timestamp": 1486967853916,
  "status": 404,
  "error": "Not Found",
  "exception": "com.exceptions.NotFoundException",
  "message": "Not Found",
  "path": "/names"
}

我只想让我的消息从服务传递并在异常中返回。但是没有人能告诉我该如何做到这一点。

1 个答案:

答案 0 :(得分:0)

使用@ControllerAdvice和@ExceptionHandler的组合,这可能会对你有帮助。

@ControllerAdvice
public class GlobalValidationResponse extends ResponseEntityExceptionHandler {

    @ExceptionHandler(NotFoundException.class)
        public ResponseEntity<?> handleEntityNotFoundException(NotFoundException ex, HttpServletRequest request, HttpServletResponse response) {

            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ValidationError(ex.getMessage()));

        }
}

ValidationError实体

public class ValidationError {

    //@JsonInclude(JsonInclude.Include.NON_EMPTY)
    private Map<String, String> errors = new HashMap<>();

    private String errorMessage;

    public ValidationError() {
        super();
    }

    public ValidationError(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public ValidationError(Map<String, String> errors) {
        this.errors = errors;
    }

    public Map<String, String> getErrors() {
        return errors;
    }

    public void setErrors(Map<String, String> errors) {
        this.errors = errors;
    }

    public String getErrorMessage() {
        return errorMessage;
    }
}
相关问题