我如何在Spring boot / mvc中创建一个错误处理程序(404,500 ...)?

时间:2016-08-04 21:31:34

标签: java spring spring-mvc spring-boot

我花了几个小时试图在Spring Boot / MVC中创建一个CUSTOM全局错误处理程序。我读过很多文章而且没什么......:/请。帮助我。

那是我的错误类:

我尝试创建类似

的类
@Controller
public class ErrorPagesController {

    @RequestMapping("/404")
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public String notFound() {
        return "/error/404";
    }

    @RequestMapping("/403")
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String forbidden() {
        return "/error/403";
    }

    @RequestMapping("/500")
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String internalServerError() {
        return "/error/500";
    }

}

****问题已解决**** 我用过这种方式:

`

@Configuration
public class ErrorConfig implements EmbeddedServletContainerCustomizer {
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
    }
}

`

5 个答案:

答案 0 :(得分:7)

@Arash 的补充 您可以添加一个可以扩展的新BaseController类,用于处理从例外到http response的转换。

     import com.alexfrndz.pojo.ErrorResponse;
     import com.alexfrndz.pojo.Error;
     import com.alexfrndz.pojo.exceptions.NotFoundException;
     import org.springframework.http.HttpStatus;
     import org.springframework.http.ResponseEntity;
     import org.springframework.web.bind.annotation.ExceptionHandler;
     import org.springframework.web.bind.annotation.ResponseBody;
     import org.springframework.web.bind.annotation.ResponseStatus;

     import javax.persistence.NoResultException;
     import javax.servlet.http.HttpServletRequest;
     import java.util.List;

     @Slf4j
     public class BaseController {

    @ExceptionHandler(NoResultException.class)
    public ResponseEntity<Exception> handleNoResultException(
            NoResultException nre) {
        log.error("> handleNoResultException");
        log.error("- NoResultException: ", nre);
        log.error("< handleNoResultException");
        return new ResponseEntity<Exception>(HttpStatus.NOT_FOUND);
    }


    @ExceptionHandler(Exception.class)
    public ResponseEntity<Exception> handleException(Exception e) {
        log.error("> handleException");
        log.error("- Exception: ", e);
        log.error("< handleException");
        return new ResponseEntity<Exception>(e,
                HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public ErrorResponse handleNotFoundError(HttpServletRequest req, NotFoundException exception) {
        List<Error> errors = Lists.newArrayList();
        errors.add(new Error(String.valueOf(exception.getCode()), exception.getMessage()));
        return new ErrorResponse(errors);
    }
   }

答案 1 :(得分:4)

您可以尝试以下代码:

@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(Exception.class)
    public ModelAndView handleError(HttpServletRequest request, Exception e)   {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
        return new ModelAndView("error");
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ModelAndView handleError404(HttpServletRequest request, Exception e)   {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Request: " + request.getRequestURL() + " raised " + e);
        return new ModelAndView("404");
    }
}

答案 2 :(得分:4)

春季启动更新

自定义错误页

如果要显示给定状态代码的自定义HTML错误页面,请将文件添加到/ error文件夹。错误页面可以是静态HTML(即添加到任何静态资源文件夹下)或使用模板构建。文件的名称应该是确切的状态代码或系列掩码。

例如,要将404映射到静态HTML文件,您的文件夹结构将如下所示

src/
 +- main/
     +- java/
     |   + <source code>
     +- resources/
         +- public/
             +- error/
             |   +- 404.html
             +- <other public assets>

Source

答案 3 :(得分:3)

@ControllerAdvice
 public class ErrorHandler {

public RestErrorHandler() {
}

@ExceptionHandler(YourException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public XXX processException(Exception ex){}

你需要一个这样的课程。为每个异常添加一个方法,并根据需要对其进行注释 - @ResponseBody等。

答案 4 :(得分:2)

希望这会有所帮助: 创建一个类说:NoProductsFoundException,它扩展了runtimexception。

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ResponseStatus;

    @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="No products found under this category")
    public class NoProductsFoundException extends RuntimeException{

    private static final long serialVersionUID =3935230281455340039L;
    }

然后在你的productcontroller中:

    @RequestMapping("/{category}")
    public String getProductsByCategory(Model
    model,@PathVariable("category") String category) {

   List<Product> products = productService.getProductsByCategory(category);

   if (products == null || products.isEmpty()) {
   throw new NoProductsFoundException ();
   }
   model.addAttribute("products", products);
   return "products";
}

enter image description here