小编典典

Spring-Boot-错误处理

spring-boot

我正在尝试为我的控制器在Spring-
Boot中编写错误处理程序,以捕获大多数可能的错误(Spring,sql等)。到目前为止,我可以通过Nulls获得JSON响应,但是我无法将任何数据放入其中。当我尝试收到错误消息时,我只会收到空白页。

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

@RestController
public class BasicErrorController implements ErrorController {
    private static final String ERROR_PATH = "/error";

    @RequestMapping(value=ERROR_PATH)
    @ExceptionHandler(value = {NoSuchRequestHandlingMethodException.class, SQLException.class, IOException.class, RuntimeException.class, Exception.class})
    public ErrorBody defaultErrorHandler(HttpServletRequest request, Exception e) {     
        ErrorBody eBody = new ErrorBody();         
        eBody.setMessage(e.getCause().getMessage());
        return eBody;
    }
}



import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class ErrorBody {
    private String dateTime;
    private String exception;
    private String url;
    private String message;
}

阅读 245

收藏
2020-05-30

共1个答案

小编典典

哟可以做这样的事情:

 @ControllerAdvice
   public class ControllerExceptionTranslator {


    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    SimpleErrorMessage handleException(EntityNotFoundException exception){
        log.debug("Entity Not Found Exception {}",exception.getMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Entity not found","This resource was not found");
    }


    @ExceptionHandler({UsernameNotFoundException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    SimpleErrorMessage handleException(UsernameNotFoundException exception){
        log.debug("Username not found {}",exception.getLocalizedMessage());
        log.trace(exception.getMessage(),exception);
        return new SimpleErrorMessage("Unaouthorized"," ");
    }


}
2020-05-30