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



这是我的 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"
}

我只希望我的消息从服务传递并在异常中返回。但这并没有发生,谁能告诉我该怎么做。

使用@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()));
        }
}

验证错误的实体

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;
    }
}

最新更新